Django Rest Framework: empty request.data - python

I have the following code for a view of DRF:
from rest_framework import viewsets
class MyViewSet(viewsets.ViewSet):
def update(self, request, pk = None):
print pk
print request.data
I call the URL via python-requests in the following way:
import requests
payload = {"foo":"bar"}
headers = {'Content-type': 'application/json'}
r = requests.put("https://.../myPk", data= payload, headers=headers)
but when the request is received from the server, request.data is empty. Here there is the output:
myPk
<QueryDict: {}>
How can I fix this problem?

You need to send the payload as a serialized json object.
import json
import requests
payload = {"foo":"bar"}
headers = {'Content-type': 'application/json'}
r = requests.put("https://.../myPk/", data=json.dumps(payload), headers=headers)
Otherwise what happens is that DRF will actually complain about:
*** ParseError: JSON parse error - No JSON object could be decoded
You would see that error message by debugging the view (e.g. with pdb or ipdb) or printing the variable like this:
def update(self, request, pk = None):
print pk
print str(request.data)

Check 2 issues here:-
Json format is proper or not.
Url is correct or not(I was missing trailing backslash in my url because of which I was facing the issue)
Hope it helps

Assuming you're on a new enough version of requests you need to do:
import requests
payload = {"foo":"bar"}
r = requests.put("https://.../myPk", json=payload, headers=headers)
Then it will properly format the payload for you and provide the appropriate headers. Otherwise, you're sending application/x-www-urlformencoded data which DRF will not parse correctly since you tell it that you're sending JSON.

Related

Request API POST

I'm having a problem with a Python request, where I pass the body url to the API data.
Note: I have a Node.js project with TypeScript that works normally, prints to the screen and returns values. However if I try to make a request in Python it doesn't work with an error 401.
Below is an example of how the request is made in Python. can you help me?
import requests
url = 'https://admins.exemple'
bodyData = {
'login': 'admins',
'pass': 'admin',
'id': '26' }
headers = {'Content-Type': 'application/json'}
resp = requests.post(url, headers=headers, data=bodyData)
data = resp.status_code
print(data)
Please dump a dict to a json string as follows:
import json
resp = requests.post(url, headers=headers, data=json.dumps(bodyData))
You also can pass your dict to json kwarg
resp = requests.post(url, headers=headers, json=bodyData)
It will set Content-Type: application/json and dump dict to json automatically
You are not correctly authenticating with the server. Usually, you need to send the username and password to a "sign in" route which will then return a token. Then you pass the token with other requests to get authorization. Since I don't know any details about your server and API, I can't provide any more details to help you out.

Python: While using the requests library and an API, how do I change the header "Content-Type" to JSON?

I've been trying to use an api on a website for awhile now and the responses from the api return the data in xml. I want the response to be in JSON format, but when I try adding a header into the http request, it keeps sending the response in xml.
I've tried the following code:
import requests
param_list = {'key1': 'value1'}
headers = {'Content-Type': 'application/json'}
url = 'api url'
response = requests.get(url=url, params=param_list, headers=headers,)
print(response.text)
print(response.headers)
The second print statement shows that the 'Content-Type' header returns "text/html"
Any idea on how to fix this? Thanks for your time and help!

How to add headers and body to a python request

I created a GET request in Python for an API and I would like to add headers and body
import urllib2
import os
proxy = 'http://26:Do#proxy:8080'
os.environ['http_proxy'] = proxy
os.environ['https_proxy'] = proxy
os.environ['HTTP_PROXY'] = proxy
os.environ['HTTPS_PROXY'] = proxy
contents = urllib2.urlopen("https://xxxx/lista?zile=50 ").read()
I tried in Postman and I received a response and I would like to receive the same response in python. How can I add headers and body ?
Thanks in advance
You can use the urlopen function with a Request object:
https://docs.python.org/2/library/urllib2.html#urllib2.urlopen
This Request object can contain headers and body:
https://docs.python.org/2/library/urllib2.html#urllib2.Request
Example: https://docs.python.org/2/howto/urllib2.html#data
P.S: HTTP GET requests don't have a body. Maybe you meant POST or PUT?
the best way is to use the request library which is pretty simple to use. https://realpython.com/python-requests/
example:
import requests
headers = {'Content-Type': 'application/json'}
data_json = {"some_key": "some_value"}
response = requests.post("https://xxxx/lista?zile=50", headers=headers, json=data_json)

Posting a json data in url -- Python

I have JSON data stored in a variable in [{"totalspend": 3240.650785131, "dailybudget": 50.0}] format.
I am trying to post this JSON data to a url using:
import requests
r = requests.post("myurl", myjson)
but I am not able to see the result on my url after executing the code.
Your server most likely expects the Content-Type: application/json header to be set:
r = requests.post("myurl", data=myjson,
headers={'Content-Type': 'application/json'})
Do make sure that myjson is an actual JSON string and not a Python list.
If you are using requests version 2.4.2 or newer, you can leave the encoding of the JSON data entirely to the library; it'll set the correct Content-Type header for you automatically. You'd pass in the Python object (not a JSON string) to the json keyword argument:
r = requests.post("myurl", data=myobject)
You need to set headers first :
Try :
import json
import requests
payload = {"totalspend": 3240.650785131, "dailybudget": 50.0}
headers = {'content-type': 'application/json'}
r = requests.post(url, data=json.dumps(payload), headers=headers)

BLS API data using cURL and requests library?

All, I'm trying to implement a curl request to get data from the BLS. Following their example here (they show the curl request), my code looks like this:
import requests
headers = {'Content-type': 'application/json'}
params = {"seriesid":["LEU0254555900", "APU0000701111"],"startyear":"2002", "endyear":"2012"}
p = requests.post('http://api.bls.gov/publicAPI/v1/timeseries/data/', params = params,headers = headers)
print p.url
print p.content
I'm getting the following (error) output:
http://api.bls.gov/publicAPI/v1/timeseries/data/?seriesid=LEU0254555900&seriesid=APU0000701111&endyear=2012&startyear=2002
{"status":"REQUEST_FAILED","responseTime":0,"message":["Sorry, an
internal error occurred. Please check your input parameters and try
your request again."],"Results":null}
Anyone had to deal with the BLS api and python?
Is the requests library the best for this?
You need to send the data as json, not pass it as a params dict. params sets the url parameters, which is not what you want, you need to pass it as data.
This should work:
import requests
import json
headers = {'Content-type': 'application/json'}
data = json.dumps({"seriesid":["LEU0254555900", "APU0000701111"],"startyear":"2002", "endyear":"2012"})
p = requests.post('http://api.bls.gov/publicAPI/v1/timeseries/data/', data=data, headers=headers)
print p.url
print p.content

Categories