Receiving incorrect response from posting JSON to an URL - python

I'm trying to post JSON to an URL but the response seems to be wrong.
url = "www.example123.com/someurl"
mypayload = { //JSON PAYLOAD }
response = request.post(url, post = payload, auth = ("USERNAME", "PASSWORD"))
print(response.content)
But it does not seem to work. What is wrong with the code?

You need the appropriate header for the specifying its JSON data.
Try :
headers_JSON = {'content-type': 'application/json'}
response = request.post(url, JSON = mypayload, headers = headers_JSON, auth = ("USERNAME", "PASSWORD"))
Also note, instead of post = payload, use JSON = payload.
If that doesn't work use:
post = JSON.dumps(payload)
A quick look at the documentation will help : http://docs.python-requests.org/en/master/user/quickstart/

var retval = jQuery.ajax({
type:'post',
url: url,
contentType: 'application/json',
data: JSON.stringify(data)
});
You can see in above jquery ajax we are setting content Type to "application/json"
You can see in your request payload what it is. It all depends upon what your server API is expecting means Content Type.

Related

Problem sending post requests to spotify api in python

def queue_song(session_id):
song_uri='spotify:track:5RwV8BvLfX5injfqYodke9'
tokens = get_user_tokens(session_id)
headers = {'Content-Type': 'application/json',
'Authorization': "Bearer " + tokens.access_token,
}
url = BASE_URL +'player/queue'
data={
'uri':song_uri
}
response = requests.post(url,headers=headers,data=data).json()
print(response)
Output:
{'error': {'status': 400, 'message': 'Required parameter uri missing'}}
https://developer.spotify.com/documentation/web-api/reference/#/operations/add-to-queue
I dont thing there is any problem with auth tokens... coz 'GET' requests are working fine
By default, using data= in requests.post() sets the content type to application/x-www-form-urlencoded which makes the body a akin to a HTTP form request.
Spotify's API is JSON based, so your data needs to be a valid json data.
You can do it in 2 ways:
response = requests.post(url,headers=headers,data=json.dumps(data)).json()
Or, more simply:
response = requests.post(url,headers=headers,json=data).json()
and in this way you don't need to manually set the application/json header as well.
Edit:
After going through the API docs you linked, there's more wrong with the call you're making.
You're sending the parameters in data - which is the body of the request. But Spotify API specifies the parameters need to be put in the Query i.e. the query string of the URI. Which means your request should be:
response = requests.post(url,headers=headers,params=data).json() # set query string not body

LinkedIn API request with Python returns "Unpermitted fields present in PARAMETER: Data Processing Exception while processing fields"

I am trying to Retrieve Statistics for Specific UGC Posts using the official documentations
My request looks like this:
requests.get(f'https://api.linkedin.com/v2/organizationalEntityShareStatistics?q=organizationalEntity&organizationalEntity=urn%3Ali%3Aorganization%3A00000&ugcPosts[0]=urn%3Ali%3AugcPost%3A111111&ugcPosts[1]=urn%3Ali%3AugcPost%3A222222', headers = headers)
"00000" is the company ID
"111111" and "222222" - are ugcPosts URNs
The headers look like this:
def headers(access_token):
'''
Make the headers to attach to the API call.
'''
headers = {
'Authorization': f'Bearer {access_token}',
'cache-control': 'no-cache',
'X-Restli-Protocol-Version': '2.0.0'
}
I have also passed the scope as one of the parameters, when authorizing:
def authorize(api_url,client_id,client_secret,redirect_uri):
# Request authentication URL
csrf_token = create_CSRF_token()
params = {
'response_type': 'code',
'client_id': client_id,
'redirect_uri': redirect_uri,
'state': csrf_token,
'scope': 'r_liteprofile,r_emailaddress,w_member_social,r_organization_social,r_1st_connections_size,r_ads_reporting,rw_organization_admin,r_basicprofile,r_ads,rw_ads,w_organization_social'
}
response = requests.get(f'{api_url}/authorization',params=params)
Unfortunately this particular request doesn't give me the response I was expecting:
{'serviceErrorCode': 100, 'message': 'Unpermitted fields present in PARAMETER: Data Processing Exception while processing fields [/ugcPosts[1], /ugcPosts[0]]', 'status': 403}
It works ok, when requesting a list of all ugcPosts
requests.get('https://api.linkedin.com/v2/ugcPosts?q=authors&authors=List(urn%3Ali%3Aorganization%3A00000)&sortBy=CREATED&count=100', headers = headers)
I have no clue what am I don't wrong. Can you please help me with my predicament?
The full request code is here
import requests
import json
from liapiauth import auth, headers
def organization_info(headers):
response = requests.get(f'https://api.linkedin.com/v2/organizationalEntityShareStatistics?q=organizationalEntity&organizationalEntity=urn%3Ali%3Aorganization%3A00000&ugcPosts[0]=urn%3Ali%3AugcPost%3A1111111&ugcPosts[1]=urn%3Ali%3AugcPost%3A2222222', headers = headers)
organization_info = response.json()
return organization_info
if __name__ == '__main__':
credentials = 'credentials.json'
access_token = auth(credentials)
headers = headers(access_token)
organization_info = organization_info(headers)
with open('lisharelist.json', 'w') as outfile:
json.dump(organization_info, outfile)
So it turns out, that the problem is in request formatting. The documentation is outdated.
The sample request looks like this:
GET https://api.linkedin.com/v2/organizationalEntityShareStatistics?q=organizationalEntity&organizationalEntity=urn:li:organization:2414183&ugcPosts[0]=urn:li:ugcPost:1000000&ugcPosts[1]=urn:li:ugcPost:1000001
Apart from changing ":" to "%3A" we also have to edit the list of ugcPosts. Here is the correct looking sample request:
GET https://api.linkedin.com/v2/organizationalEntityShareStatistics?q=organizationalEntity&organizationalEntity=urn%3Ali%3Aorganization%3A2414183&ugcPosts=List(urn%3Ali%3AugcPost%3A1000000,urn%3Ali%3AugcPost%3A1000001)

Send image in request from python

I am trying to upload an image using POST request. From Postman, it is giving success but when I try same code from python, I am getting an error (payload validation failed). Following is my code in python:
import requests
url = "http://10....."
payload = {}
files=[('pdf_file',('passport.jpg', open('/D:/passport.jpg','rb'), 'image/jpeg'))]
headers = {
'accept':'application/json',
'Content-Type':'multipart/form-data',
'Authorization':'<token_here>',
}
response = requests.request("POST", url, headers = headers, data = payload, files = files)
print(response.text)
While invoking request from postman, headers are same as above code. Select form-data in body section and upload image for key "pdf_file".
Is there any difference in both approaches?
You should omit content type from headers
headers = {
'accept':'application/json',
'Authorization':'<token_here>'
}

Swagger API and interaction with python requests

A product was purchased to enable our users to send/receive SMS over HTTP. Now it's my job to build it into our current CMS platform & database. It's got a swagger API.
Here is the documentation for the specific POST request I am trying to send:
POST: Send an SMS Message
Here is my simple python program to test the functionality. I get a generic 500 internal server error response. What am I doing incorrectly?
import requests
API_URL = "https://api.kenect.com/v1/conversations/messages"
headers = {
'x-api-token': '****************',
'x-api-key': '*******************',
'Content-Type': 'application/json',
}
params = {
'contactPhone': '158572968**',
'locationId': '2045',
'messageBody': 'test sms',
'outgoing': 'true',
}
r=requests.post(url = API_URL, headers = headers, params = params)
print(r)
There seems to be 2 issues:
Content type and payload encoding.
You are using params parameter in the post method. params is used with get method for passing data in the URL's query string.
In the post method, depending on the required content type, you need to use either data parameter to send form-encoded data:
r=requests.post(url = API_URL, headers = headers, data = params)
or json parameter to send application/json payload:
r=requests.post(url = API_URL, headers = headers, json = params)
Remove the 'Content-Type' key from your headers dictionary. data and json parameters will set up correct content type automatically.
outgoing is not a valid request parameter for the /v1/conversations/messages resource. This field is from the response object, not the request one. Remove it from your payload.
So to sum up, for form-encoded payload the code should look like this:
import requests
API_URL = "https://api.kenect.com/v1/conversations/messages"
headers = {
'x-api-token': '****************',
'x-api-key': '*******************',
}
params = {
'contactPhone': '158572968**',
'locationId': '2045',
'messageBody': 'test sms',
}
r=requests.post(url = API_URL, headers = headers, data = params)

Python requests Post request data with Django

I'm trying to send a simple post request to a very simple django server and can't wrap my head around why the post data isn't appearing in the requests post dictionary and instead its in the request body.
Client code:
payload = {'test':'test'}
headers = {'Content-type': 'application/json','Accept': 'text/plain'}
url = "localhost:8000"
print json.dumps(payload)
r = requests.post(url,data=json.dumps(payload),headers=headers)
Server Code:
def submit_test(request):
if request.method == 'POST':
print 'Post: "%s"' % request.POST
print 'Body: "%s"' % request.body
return HttpResponse('')
What is printed out on the server is:
Post: "<QueryDict: {}>"
Body: "{"test": "test"}"
I've played around with the headers and sending the data as a straight dictionary and nothing seems to work.
Any ideas? Thanks!!
The POST dictionary only contains the form-encoded data that was sent in the body of the request. The body attribute contains the raw body of the request as a string. Since you are sending json-encoded data it only shows up in the raw body attribute and not in POST.
Check out more info in the docs.
Try form-encoded data and you should see the values in the POST dict as well:
payload = {'test':'test'}
url = "localhost:8000"
requests.post(url, data=payload)
Specifying a user-agent in the headers should enable Django to interpret the raw data of the body and to correctly populate the POST dictionary. The following should work:
payload = {'test': 'test'}
url = "http://localhost:8000"
headers = {'User-Agent': 'Mozilla/5.0'}
requests.post(url, data=payload, headers=headers)
You should remove 'Content-type' from headers and use default one which is 'multipart/form-data'
response = client.post(
'/some_url/',
data={'post_key': 'some_value'},
# content_type='application/json'
)
If you uncomment 'content_type' data will be only in request.body

Categories

Resources