Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Curl Post Json data not being read in Python Django

Tags:

python

json

curl

Am using curl exe in windows, to communicate with my Django backend.

Following is the command am using.

curl --dump-header - -H "Accept: application/json" -H "Content-Type: application/json" -X POST --data "{\"uid\":12,\"token\":\"asdert\"}" http://localhost:8000/restapi/v1/foo/

Now this give the data in wrong format. i.e. in the view the post is showing this data print request.POST

{"{\"uid\":12,\"access_token\":\"asdert\"}": [""]}

What is the correct way to post json data ?

Edit:

I have tried several other methods for e.g. I am trying to communiate with my rest api using http://slumber.in/.

Even here am getting the same result as above.

import slumber
api = slumber.API("http://localhost/restapi/v1/"
api.foo.post({"uid":"100"})

Excerpts from the view print request.POST

 {u'{"uid": "100"}': [u'']}

P.S. - curl --dump-header - -H "Accept: application/json" -H "Content-Type: application/json" -X POST --data "uid=12&token=asdert" http://localhost:8000/restapi/v1/foo/

This works. But this is not Json format.

like image 369
Akash Deshpande Avatar asked Oct 21 '12 09:10

Akash Deshpande


People also ask

How pass JSON data in Curl Post?

To post JSON data using Curl, you need to set the Content-Type of your request to application/json and pass the JSON data with the -d command line parameter. The JSON content type is set using the -H "Content-Type: application/json" command line parameter. JSON data is passed as a string.

Does Curl POST request?

Users can send data with the POST request using the -d flag. The following POST request sends a user and a pass field along with their corresponding values. POSTing with curl's -d option will include a default header that looks like: Content-Type: application/x-www-form-urlencoded .

Does Curl use JSON?

To get JSON with Curl, you need to make an HTTP GET request and provide the Accept: application/json request header. The application/json request header is passed to the server with the curl -H command-line option and tells the server that the client is expecting JSON in response.


1 Answers

I tried your command with http://httpbin.org/post and it worked fine.

Now, your problem is that you should access the incoming JSON data from

request.raw_post_data

instead of request.POST.

(Or if you are using Django 1.4+, use request.body instead as request.raw_post_data is being deprecated)


Detailed code should be something like this:

import json

if request.method == "POST":
    data = json.loads(request.raw_post_data)
    print data
like image 83
K Z Avatar answered Oct 24 '22 03:10

K Z