Post data being clipped - python

When sending a post request to a python CGI server via jquery, sometimes some of the arguments are clipped. When sending the same post request again the request is received in with complete data.
I have checked the chrome browser network requests and they show that request is being fully sent.
Here is an example of a partially sent request:
var message = {
"to": "test.user#gmail.com",
"sender": "test.user#gmail.com",
"code": "K96nhC4qnIvzcM3XzaIMwfwuRjBooyHZWwtM1hIE\n2rD2WuvZ4B3/2J0xfDstsj91B/K8i7V6gjx1l/Mm\nX5skxuy6ih63ChZN3IWZjIXDCZ1F3V15/7oYDlsa\n6rgueyzEuW87nQJAmAh2P7tFEC6SQxEu/rln8DNs\nMrGSQRdMRY2kmzyVlnKbWEuZ6yjJes7TKaQ2GhL7\nSvAP4DMRl1mKSwnA7qAaCHVqG9iCPqyjy2eKJN/C\nviF7kBavfAZqcMlyY76VyMVSg3zG7t1LUfUA"
}
And the same request fully sent:
var message = {
"to": "test.user#gmail.com",
"sender": "test.user#gmail.com",
"code": "K96nhC4qnIvzcM3XzaIMwfwuRjBooyHZWwtM1hIE\n2rD2WuvZ4B3/2J0xfDstsj91B/K8i7V6gjx1l/Mm\nX5skxuy6ih63ChZN3IWZjIXDCZ1F3V15/7oYDlsa\n6rgueyzEuW87nQJAmAh2P7tFEC6SQxEu/rln8DNs\nMrGSQRdMRY2kmzyVlnKbWEuZ6yjJes7TKaQ2GhL7\nSvAP4DMRl1mKSwnA7qAaCHVqG9iCPqyjy2eKJN/C\nviF7kBavfAZqcMlyY76VyMVSg3zG7t1LUfUAhsMN\nXWSoVzG/kmKJen3czBo74UT8s0eUXCtFa01Hfecv\nGbQVBHHlTCrz3y5IoOqUQQDHtzE5oke7TL46nv52\nhwr1Q0/Sc9+QXA+rd/iMOWKjEY+AfbizI5K6v4VJ\nlP6wEL1Wo49f5haAukgJ6kWjx4hI8dcwEKrM5kbR\nDqQ3nQuIAnYM+8NeMmfjgoS4ReovtjQPjN/dk+eP\nEGiF8XWkIHHuerORq/9PERxeitJcZEWWYSkmjPu9\n8mW4K3jSm0SG3LV+E6mOx3uycCYkh9O1mqfwBk+3\nEE8litsIJ84ivZ+FzPZsbI0u9w3zsKE="
}
Both examples are JSON formatted from server logs.
Here is the javascript:
$.post('cgi-bin/somescript.py', message, someCallback, 'text')

Your 'data' should be a stringified Javascript object:
data: JSON.stringify({ "userName": userName, "password" : password })
Or, to send the data from the form, pass it formData, like this:
data: JSON.stringify(formData)
There's also a more detailed answer to a similar question here: Jquery Ajax Posting json to webservice
orginal answer

Related

Put/Post errors while trying to access it from through python. "Bad Request. The JSON payload should be inside a root property called

I am trying to post/put to Sheety via Python:
SHEETY_URL = "https://api.sheety.co/gfhgfhjfdghjgfjf/flightDeals/prices/5"
header = {
"Content-Type" : "application/json"
}
params_sheety = {
"price": {
"iataCode": "PLN"
}
}
response_sheety = requests.put(url=SHEETY_URL, params=params_sheety, headers=header)
print(response_sheety)
print(response_sheety.json())
=======================================================
Getting Bad request Error:
<Response [400]> {'errors': [{'detail': "Bad Request. The JSON payload
should be inside a root property called 'price'. Check
https://sheety.co/docs for more details."}]}
The same request works fine with Postman.
When you use params=params_sheety, the parameters are not sent as json.
Use json=params_sheety to send them as json.
This also sets the content-type header to json automatically, so you don't need headers=header.

Value is not a valid dict when posting JSON data through Postman to FastAPI backend

#app.post("/posts")
def post_req(payload: dict = Body(...)):
print(payload)
return {"Message": "Posted!!!"}
I am using the above path operation function to receive POST requests, but when I am trying to make a request using Postman, it says value is not a valid dict.
In Postman I am sending the below in the request body:
{
"title" : "This is title"
}
The response I get in Postman is as follows:
{
"detail": [
{
"loc": [
"body"
],
"msg": "value is not a valid dict",
"type": "type_error.dict"
}
]
}
VS Code terminal (server side) is showing this:
127.0.0.1:51397 - "POST /posts HTTP/1.1" 422 Unprocessable Entity
When defining your payload Body parameter like this:
payload: dict = Body(...)
and since it is the only Body parameter in your endpoint, FastAPI will expect a body like:
{
"some key": "some value"
}
Since you have a single body parameter, you could also use the special Body parameter embed:
payload: dict = Body(..., embed=True)
in which case, FastAPI would expect a body like:
{
"payload": {"some key": "some value"}
}
Please have a look at this answer, as well as this answer and this answer for more details.
When sending the request through Postman
Also, the 422 Unprocessable Entity error shows that the body received doesn't match the expected format. Hence, please make sure you are posting the request body through Postman in the right way. That is, go to Body -> raw, and select JSON from the dropdown list to indicate the format of your data. Please take a look at the answers here and here for more details.
You need to do:
{
"payload": {"title": "This is title"}
}
Select data type that you are sending as json in postman.
This will 100% resolve your error.

Graphen Django: Batch requests should receive a list, but received {'query': XXX}

I have enabled the batch query processing functionality in Graphene-Django by adding batch=True to the .as_view(...) method as,
urlpatterns = [
# other URL patterns,
path('graphql/', CustomGraphQLView.as_view(schema=schema, batch=True), name='graphql')
]
After that, I sent the request (see below screenshot) with a query to the server using Postman client, but got an error
GraphQL Query
{
musicians {
id
name
}
}
Error Response
{
"errors": [
{
"message": "Batch requests should receive a list, but received {'query': 'bla bla'}"
}
] }
Postman Screenshot
Question
What is the proper way to send the GraphQL batch requests to Graphene-Django?
How can I send GraphQL batch requests to Graphene-Django using Postman client?
The Graphene-Django expects the queries as a list of dicts (or JSON Array of JSON Objects).
So you need to build a payload as,
[
{
"query": "{musicians{id}}"
},
{
"query": "{musicians{name}}"
},
{
"query": "{musicians{id,name,}}"
}
]
Make sure that, the request should be sent as raw JSON from the POSTMAN client (or any non-GraphQL client)
Result Screenshot

How to send json POST request using requests if the website uses jwt?

i am trying to send POST request to login to this URL
, i first checked the network tab and found out the the post request is being sent to this
url : https://api-my.te.eg/api/user/login?channelId=WEB_APP
and the request payload is:
{
"header":{
"timstamp":0,
"customerId":null,
"msisdn":null,
"messageCode":null,
"responseCode":"1200",
"responseMessage":"Your Session has been expired, please sign in to continue",
"locale":null,
"referenceId":null,
"channelId":null,
"responeAdditionalParameters":null
},
"body":null
}
Here is the code :
import requests
import calendar
import time
#Here i tried to send a generated timestamp, idk if this is needed or not
ts = calendar.timegm(time.gmtime())
loginUrl = 'https://api-my.te.eg/api/user/login?channelId=WEB_APP'
values = {
"msisdn": MobileNumberID,
"timestamp": str(ts),
"locale": "Ar"
}
data = {
"password": PasswordID
}
url = requests.post(loginUrl , data=data , headers=values)
print(url.text)
I looked at the site and in the body they are also passing a header property in the data
So you should use
data = {
"header": {
"msisdn": "024568478",
"timestamp": "1592337873",
"locale": "Ar"
},
"body": {
"password": "PJGkRJte5ntnKt9TQ8XM3Q=="
}
}
and in headers you should pass the native headers probably something like:
headers={'Content-Type': 'application/json', }
but i also see by when you log into this site they pass a jwt argument in the headers. Looks like its some sort of built in security. So it looks like you can not use this API. Its only for the backend of this site.
Did you search the site to see if they have API documentation, maybe their is written how you can calculate the value for jwt?
EDIT:
When you get the login working this is. How to use sessions in python requests:
s = requests.Session()
data = {"login":"my_login", "password":"my_password"}
url = "http://example.net/login"
r = s.post(url, data=data)
If you do not get arround the jwt. You can uses Selenium in python. It works by automating a webbrowser. So you can open chrome tell it wich page to load, fill in your login form and read the html of elements in the browser. This will work on 95% of the websites. Some even have protections against it. Some sites use cloudflare, they are protected from selenium automation.

Can not parse JSON share document.\nRequest body:\n\nError:\nnull

I am trying to send a request to Linkedin's rest share api. I have been receiving this error message:
{
"errorCode": 0,
"message": "Can not parse JSON share document.\nRequest body:\n\nError:\nnull",
"requestId": "ETX9XFEI7N",
"status": 400,
"timestamp": 1437910620120
}
The request is send through the following python code:
import requests,json
auth_token = "some auth token"
url = "https://api.linkedin.com/v1/people/~/shares?format=json&oauth2_access_token="+auth_token
headers = {'content-type': 'application/x-www-form-urlencoded','x-li-format':'json'}
data = {
"comment":"Check out developer.linkedin.com!",
"content":{
"title": "LinkedIn Developers Resources",
"description": "Leverage LinkedIn's APIs to maximize engagement",
"submitted-url": "https://developer.linkedin.com",
"submitted-image-url": "https://example.com/logo.png"
},
"visibility":{
"code": "anyone"
}
}
response = requests.post( url , json= data , headers=headers )
return HttpResponse( response )
I made sure that I followed all the instructions in their documentation and can't find the mistake I am making.
Note: i have tried json=data and data=data both are not working
Remove content-type from the headers dictionary.
requests sets the correct Content-Type when using the json keyword argument.
You have three basic problems:
Please read the documentation on oauth2; because you are not passing in the token correctly.
The share URL does not take a oauth2_token argument.
You have the wrong content-type header.

Categories

Resources