Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to make post request in python

Tags:

python

curl

Here is the curl command:

curl -H "X-API-TOKEN: <API-TOKEN>" 'http://foo.com/foo/bar' --data # 

let me explain what goes into data

POST /foo/bar
Input (request JSON body)

Name    Type    
title   string  
body    string

So, based on this.. I figured:

curl -H "X-API-TOKEN: " 'http://foo.com/foo/bar' --data '{"title":"foobar","body": "This body has both "double" and 'single' quotes"}'

Unfortunately, I am not able to figure that out as well (like curl from cli) Though I would like to use python to send this request. How do i do this?

like image 516
frazman Avatar asked Feb 12 '15 01:02

frazman


People also ask

How do you send a POST request in Python?

We use requests. post() method since we are sending a POST request. The two arguments we pass are url and the data dictionary. In response, the server processes the data sent to it and sends the pastebin URL of your source_code which can be simply accessed by r.

How does Python requests post work?

Understanding the Python requests POST FunctionAn HTTP POST request is used to send data to a server, where data are shared via the body of a request. In the request. post() function, data are sent with the data parameter, which accepts a dictionary, a list of tuples, bytes or a file object.

How do you send data in a POST request?

To send data using the HTTP POST method, you must include the data in the body of the HTTP POST message and specify the MIME type of the data with a Content-Type header. Below is an example of an HTTP POST request to send JSON data to the server. The size and data type for HTTP POST requests is not limited.


1 Answers

With the standard Python httplib and urllib libraries you can do

import httplib, urllib

headers = {'X-API-TOKEN': 'your_token_here'}
payload = "'title'='value1'&'name'='value2'"

conn = httplib.HTTPConnection("heise.de")
conn.request("POST", "", payload, headers)
response = conn.getresponse()

print response

or if you want to use the nice HTTP library called "Requests".

import requests

headers = {'X-API-TOKEN': 'your_token_here'}
payload = {'title': 'value1', 'name': 'value2'}

r = requests.post("http://foo.com/foo/bar", data=payload, headers=headers)
like image 96
cangoektas Avatar answered Oct 04 '22 01:10

cangoektas