Ошибка 400 питон

I am writing a python script which will call a REST POST endpoint but in response I am getting 400 Bad Request where as if I do same request with curl, it returns me 200 OK. Code snippet for python script is below

import httplib,urllib
def printText(txt):
  lines = txt.split('n')
  for line in lines:
      print line.strip()

httpServ = httplib.HTTPConnection("127.0.0.1", 9100)
httpServ.connect()

params = urllib.urlencode({"externalId": "801411","name": "RD Core","description": "Tenant create","subscriptionType": "MINIMAL","features":   {"capture":False,"correspondence": True,"vault": False}})

 headers = {"Content-type": "application/json"}
 httpServ.request("POST", "/tenants", params, headers)
 response = httpServ.getresponse()
 print response.status, response.reason
 httpServ.close()

and corresponding curl request is

curl -iX POST 
-H 'Content-Type: application/json' 
-d '
{
    "externalId": "801411",
    "name": "RD Core seed data test",
    "description": "Tenant for Core team  seed data testing",
    "subscriptionType": "MINIMAL",
    "features": {
        "capture": false,
        "correspondence": true,
        "vault": false
    }
}' http://localhost:9100/tenants/

Now I am not able figure out where is the issue in python script.

Andrei1penguin1, по разному настроены серверы, принимают контент разного типа.
json в requests просто форматирует стандартный словарь в валидную JSON строку, добавляет соответствующий заголовк Content-Type и отправляет запрос. Передавая информацию в data — передается стандартный Content-Type. В принципе, можно хоть вручную установить Content-Type на json, сделать dumps и передать все это в data.

import requests
import json
data = {
    "phone_number": "+77777777777"
}
headers = {'Content-Type': 'application/json'}
response = requests.post("https://eda.yandex.ru/api/v1/user/request_authentication_code", data=json.dumps(data), headers=headers)
print(response.text)

Answer by Hendrix Morris

The HyperText Transfer Protocol (HTTP) 400 Bad Request response status code indicates that the server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing).,HTTP response status codes,Warning: The client should not repeat this request without modification.,

HTTP guide

Basics of HTTP
Overview of HTTP
Evolution of HTTP
HTTP Messages
A typical HTTP session
Connection management in HTTP/1.x
Protocol upgrade mechanism

400 Bad Request

Answer by Averi Duncan

Also, enclose your data as JSON in the request body, don’t pass them as URL parameters. You are passing JSON data in your curl example as well.,and corresponding curl request is ,Please be sure to answer the question. Provide details and share your research!,Making statements based on opinion; back them up with references or personal experience.

Also, enclose your data as JSON in the request body, don’t pass them as URL parameters. You are passing JSON data in your curl example as well.

import requests


data = {
    "externalId": "801411",
    "name": "RD Core",
    "description": "Tenant create",
    "subscriptionType": "MINIMAL",
    "features": {
        "capture": False,
        "correspondence": True,
        "vault": False
    }
}

response = requests.post(
    url="http://localhost:9100/tenants/",
    json=data
)

print response.status_code, response.reason

Answer by Melani Patrick

The 400 (Bad Request) status code indicates that the server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing).,The key concept to understand here is that the 400 Bad Request error is something that has to do with the submitted request from the client before it is even processed by the server.,The 400 Bad Request Error is an HTTP response status code
that indicates the server was unable to process (understand) the request sent by the client due to incorrect syntax, invalid request message framing, or deceptive request routing.,The 4xx family of status codes is the one we’re investigating here as they relate to invalid or corrupt requests from the client. Specifically, we’ll take a closer look at the 400 Bad Request error: what this error means, what causes it as well as some specific steps to fix the issue.

This is surprisingly easy to do by mistake and can happen if a URL has been encoding incorrectly. The following link is an example of a URL containing characters the server won’t be able to process, hence a 400 Bad Request error is triggered.

https://twitter.com/share?lang=en&text=Example%20of%20malformed%%20characters%20in%20URL

https://twitter.com/share?lang=en&text=Example%20of%20malformed%%20characters%20in%20URL

Answer by Dexter English

I received this error and got this error message: The content value must be a string at least one character in length.,Recommend double-checking to make sure your code is not violating any of those requirements and, if not, filing a support ticket to further debug the request.,I am having the same error using flask-sendgrid. I have the latest version of sendgrid installed. When launching my flask server, I can send one email fine then when I request to send another one it fails.,Thanks @linehammer, I figured that out ? As I stated in my other issue (sendgrid/python-http-client#133), it seems that flask-sendgrid send twice the to parametter after the second request.

sudo pip3 install sendgrid 

Answer by Beatrice Dunlap

The Box APIs uses HTTP status codes to communicate if a request
has been successfully processed or not.,Please check our Developer Troubleshooting Articles
for solution to common errors encountered when working with the Box APIs.,Please see the Client Error resource for more details.,Code samples provided under Unilicense

{
  "type": "error",
  "status": 400,
  "code": "bad_digest",
  "help_url": "http://developers.box.com/docs/#errors",
  "message": "The specified content-md5 did not match what we received",
  "request_id": "abcdef123456"
}

Answer by Zahra Salgado

The Client application gets the following response code:,400 Bad request — plain HTTP request sent to HTTPS port,400 Bad request — SSL certificate error,The client application receives an HTTP 400 — Bad request response with the
message «The SSL certificate error». This error is typically sent by the Edge Router
in a two way TLS setup enabled for the incoming connection to Apigee Edge.

The Client application gets the following response code:

HTTP/1.1 400 Bad Request

Followed by the below HTML error page:

<html>
  <head>
    <title>400 The SSL certificate error</title>
  </head>
  <body bgcolor="white">
    <center> <h1>400 Bad Request</h1>
    </center>
    <center>The SSL certificate error</center>
    <hr>
    <center>nginx</center>
  </body>
</html>

Typically a virtual host for two-way TLS communication looks as follows:

<VirtualHost name="myTLSVHost">
    <HostAliases>
        <HostAlias>api.myCompany.com</HostAlias>
    </HostAliases>
    <Port>443</Port>
    <SSLInfo>
        <Enabled>true</Enabled>
        <ClientAuthEnabled>true</ClientAuthEnabled>
        <KeyStore>ref://myKeystoreRef</KeyStore>
        <KeyAlias>myKeyAlias</KeyAlias>
        <TrustStore>ref://myTruststoreRef</TrustStore>
    </SSLInfo>
</VirtualHost>

Once you’ve decided where you would like to capture TCP/IP packets, use the following
tcpdump
command to capture TCP/IP packets:

tcpdump -i any -s 0 host <IP address> -w <File name>

Typically a virtual host for two-way TLS communication looks as follows:

    <VirtualHost name="myTLSVHost">
        <HostAliases>
            <HostAlias>api.myCompany.com</HostAlias>
        </HostAliases>
        <Port>443</Port>
        <SSLInfo>
            <Enabled>true</Enabled>
            <ClientAuthEnabled>true</ClientAuthEnabled>
            <KeyStore>ref://myKeystoreRef</KeyStore>
            <KeyAlias>myKeyAlias</KeyAlias>
                <TrustStore>ref://myCompanyTruststoreRef</TrustStore>
        </SSLInfo>
    </VirtualHost>

Typically a virtual host for two-way TLS communication looks as follows:

    <VirtualHost name="myTLSVHost">
        <HostAliases>
            <HostAlias>api.myCompany.com</HostAlias>
        </HostAliases>
        <Port>443</Port>
        <SSLInfo>
            <Enabled>true</Enabled>
            <ClientAuthEnabled>true</ClientAuthEnabled>
            <KeyStore>ref://myKeystoreRef</KeyStore>
            <KeyAlias>myKeyAlias</KeyAlias>
            <TrustStore>ref://myCompanyTruststoreRef</TrustStore>
        </SSLInfo>
    </VirtualHost>

openssl

openssl -in <OrgName_envName_vhostName-client.pem> -text -noout

Restart the Router to ensure the latest Certificates are loaded using the below step:

apigee-service edge-router restart

Answer by Ember Nava

The following table lists all the codes that can appear as code attribute of an <error> element if an error has occurred. ,If error messages have been translated, they are returned in the language that’s set in the Accept-Language header of the request. For example, if the headers include Accept-Language: de-de, error messages are returned in German. ,Note: You should not rely on specific text appearing in the <detail> element of an error response. Instead, test the value of the error code attribute to determine why an operation failed.,An HTTP status code of 404 for the response tells you that the operation was not successful because a resource could not be found. In that case, the response body might look like the following example:

For error conditions, the response body also includes an XML block that provides details about the error. For example, if the HTTP response was 404, the response body provides details about what resource in particular was not found. Imagine that you send the following PUT request in order to update information for a user:

http://your-server/api/3.13/sites/9a8b7c6d5-e4f3-a2b1-c0d9-e8f7a6b5c4d/users/9f9e9d9c8-b8a8-f8e7-d7c7-b7a6f6d6e6d

http://your-server/api/3.13/sites/9a8b7c6d5-e4f3-a2b1-c0d9-e8f7a6b5c4d/users/9f9e9d9c8-b8a8-f8e7-d7c7-b7a6f6d6e6d

Answer by Ezra Mora

Errors in Microsoft Graph are returned using standard HTTP status codes, as well as a JSON error response object.,The following table lists and describes the HTTP status codes that can be returned.,The error resource is returned whenever an error occurs in the processing of a request.,The code property contains one of the following possible values. Your apps should be
prepared to handle any one of these errors.

The error response is a single JSON object that contains a single property
named error. This object includes all the details of the error. You can use the information returned here instead of or in addition to the HTTP status code. The following is an example of a full JSON error body.

{
  "error": {
    "code": "invalidRange",
    "message": "Uploaded fragment overlaps with existing data.",
    "innerError": {
      "requestId": "request-id",
      "date": "date-time"
    }
  }
}

The error resource is composed of these resources:

{
  "error": { "@odata.type": "odata.error" }  
}

Inside the error response is an error resource that includes the following
properties:

{
  "code": "string",
  "message": "string",
  "innererror": { "@odata.type": "odata.error" }
}

To verify that an error object is an error you are expecting, you must loop
over the innererror objects, looking for the error codes you expect. For example:

public bool IsError(string expectedErrorCode)
{
    OneDriveInnerError errorCode = this.Error;
    while (null != errorCode)
    {
        if (errorCode.Code == expectedErrorCode)
            return true;
        errorCode = errorCode.InnerError;
    }
    return false;
}

The urllib.error.HTTPError is a class in the Python urllib library that represents an HTTP error. An HTTPError is raised when an HTTP request returns a status code that represents an error, such as 4xx (client error) or 5xx (server error).

HTTPError Attributes

The urllib.error.HTTPError class has the following attributes:

  • code: The HTTP status code of the error.
  • reason: The human-readable reason phrase associated with the status code.
  • headers: The HTTP response headers for the request that caused the HTTPError.

What Causes HTTPError

Here are some common reasons why an HTTPError might be raised:

  • Invalid or malformed request URL.
  • Invalid or malformed request parameters or body.
  • Invalid or missing authentication credentials.
  • Server internal error or malfunction.
  • Server temporarily unavailable due to maintenance or overload.

Python HTTPError Examples

Here are a few examples of HTTP errors in Python:

404 Not Found


import urllib.request
import urllib.error

try:
    response = urllib.request.urlopen('http://httpbin.org/status/404')
except urllib.error.HTTPError as err:
    print(f'A HTTPError was thrown: {err.code} {err.reason}')

In the above example, an invalid URL is attempted to be opened using the urllib.request.urlopen() function. Running the above code raises an HTTPError with code 404:


A HTTPError was thrown: 404 NOT FOUND

400 Bad Request


import urllib.request

try:
    response = urllib.request.urlopen('http://httpbin.org/status/400')
except urllib.error.HTTPError as err:
    if err.code == 400:
        print('Bad request!')
    else:
        print(f'An HTTP error occurred: {err}')

In the above example, a bad request is sent to the server. Running the above code raises a HTTPError with code 400:


Bad request!

401 Unauthorized


import urllib.request
import urllib.error

try:
    response = urllib.request.urlopen('http://httpbin.org/status/401')
except urllib.error.HTTPError as err:
    if err.code == 401:
        print('Unauthorized!')
    else:
        print(f'An HTTP error occurred: {err}')

In the above example, a request is sent to the server with missing credentials. Running the above code raises a HTTPError with code 401:


Unauthorized!

500 Internal Server Error


import urllib.request
import urllib.error

try:
    response = urllib.request.urlopen('http://httpbin.org/status/500')
except urllib.error.HTTPError as err:
    if err.code == 500:
        print('Internal server error!')
    else:
        print(f'An HTTP error occurred: {err}')

In the above example, the server experiences an error internally. Running the above code raises a HTTPError with code 500:


Internal server error!

How to Fix HTTPError in Python

To fix HTTP errors in Python, the following steps can be taken:

  1. Check the network connection and ensure it is stable and working.
  2. Check the URL being accessed and make sure it is correct and properly formatted.
  3. Check the request parameters and body to ensure they are valid and correct.
  4. Check whether the request requires authentication credentials and make sure they are included in the request and are correct.
  5. If the request and URL are correct, check the HTTP status code and reason returned in the error message. This can give more information about the error.
  6. Try adding error handling code for the specific error. For example, the request can be attempted again or missing parameters can be added to the request.

Track, Analyze and Manage Errors With Rollbar

Managing errors and exceptions in your code is challenging. It can make deploying production code an unnerving experience. Being able to track, analyze, and manage errors in real-time can help you to proceed with more confidence. Rollbar automates error monitoring and triaging, making fixing Python errors easier than ever. Try it today!

Python 400 client error Bad request for URL Azure cognitive services

In this Azure tutorial, we will discuss how to fix the error Python 400 client error: Bad request for URL Azure cognitive services. that I got while working with a requirement to Analyze an image using the Azure cognitive services Computer Vision API and Python.

  • Build Intelligent C# Apps With Azure Cognitive Services

Table of Contents

  • Python 400 client error: Bad request for URL Azure cognitive services
  • Python 400 client error: Bad request for URL Azure cognitive services [Solved]
  • Wrapping Up

Recently, I was working with a requirement where I had to get the details of an image using the Azure cognitive services Computer Vision API using Python. While running the application I got the error Python 400 client error: Bad request for URL Azure cognitive services.

Python 400 client error: Bad request for URL Azure cognitive services

This error Python 400 client error: Bad request for URL Azure cognitive services is mostly due to the below Problems

1- First thing is there might be some problem with the image, you are using here.

2- There might be some problem with the API Endpoint URL.

In my case, there was some issue with my Image so I got this error. There might be a chance you will also get the same error.

Python 400 client error: Bad request for URL Azure cognitive services [Solved]

Now, to fix this error, I have tried many ways, but at the end, I was getting the same error. Then I tried using another image and this time it was working as expected with out any issue. Few key things you need to verify if you are getting this error

  1. Verify the image properly like image size, format, etc. If you are getting the error with one image, try with another image, It might work for you.
  2. The second important thing is to check the API endpoint URL if it is properly formatted with the proper region, version, and all the parameters needed.
  3. Check the Azure cognitive services API key value properly. If needed ReGenerate the key and use the new one.

You can try to use the EndPoint URL like below

key = "d38b4303c2774962a####ed43ff4b76f"
assert apikey
url = "https://southeastasia.api.cognitive.microsoft.com/vision/v3.0/"
analyse_api = url + "analyze"
image_data = img
headers = {"Ocp-Apim-Subscription-Key": key,
'Content-Type': 'application/octet-stream'}
params = {'visualFeatures':'Categories,Description,Color,Objects,Faces'}
response = requests.post(
    analyse_api, headers=headers, params=params, data=image_data)
response.raise_for_status()
analysis = response.json()

//Rest of the code based on your functionality

This is how you can able to fix the error ” Python 400 client error: Bad request for URL Azure cognitive services “.

You may also like following the below articles

  • CS1061 C# ‘HttpRequest’ does not contain a definition for ‘Content’ and no accessible extension method ‘Content’ accepting a first argument of type ‘HttpRequest’ could be found
  • Failed To Validate The Notification URL SharePoint Webhook Azure Function Endpoint
  • How To Implement Azure Face API Using Visual Studio 2019
  • How To Convert m4a File To Text Using Azure Cognitive Services
  • Web deployment task failed – cannot modify the file on the destination because it is locked by an external process

Wrapping Up

Well, in this article, we have discussed how to fix Python 400 client error: Bad request for URL Azure cognitive services, Python-requests exceptions HTTP error 400 client error: bad request for URL. Hope this will help you to fix your issue as well !!!

Понравилась статья? Поделить с друзьями:
  • Ошибка 400 невозможно определить csrf что это
  • Ошибка 400 неверный запрос как исправить
  • Ошибка 400 на ютубе на телефоне что делать
  • Ошибка 400 на сайте что это означает
  • Ошибка 400 на портале поставщиков