Making a POST request
This example explains how to paste your source_code to pastebin.com by sending a POST request to the PASTEBIN API. First of all, you will need to generate an API key by signing up here and then accessing your API key here.
Python3
# importing the requests library import requests # defining the api-endpoint API_ENDPOINT = "http://pastebin.com/api/api_post.php" # your API key here API_KEY = "XXXXXXXXXXXXXXXXX" # your source code here source_code = ''' print("Hello, world!") a = 1 b = 2 print(a + b) ''' # data to be sent to api data = { 'api_dev_key' : API_KEY, 'api_option' : 'paste' , 'api_paste_code' : source_code, 'api_paste_format' : 'python' } # sending post request and saving response as response object r = requests.post(url = API_ENDPOINT, data = data) # extracting response text pastebin_url = r.text print ( "The pastebin URL is:%s" % pastebin_url) |
Important features of this code:
data = {'api_dev_key':API_KEY, 'api_option':'paste', 'api_paste_code':source_code, 'api_paste_format':'python'}
Here again, we will need to pass some data to the API server. We store this data as a dictionary.
r = requests.post(url = API_ENDPOINT, data = data)
Here we create a response object ‘r’ which will store the request-response. We use requests.post() method since we are sending a POST request. The two arguments we pass are the URL and the data dictionary.
pastebin_url = r.text
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.text.
requests.post method could be used for many other tasks as well like filling and submitting the web forms, posting on your FB timeline using the Facebook Graph API, etc.
Here are some important points to ponder upon:
- When the method is GET, all form data is encoded into the URL and appended to the action URL as query string parameters. With POST, form data appears within the message body of the HTTP request.
- In the GET method, the parameter data is limited to what we can stuff into the request line (URL). Safest to use less than 2K of parameters, some servers handle up to 64K.No such problem in the POST method since we send data in the message body of the HTTP request, not the URL.
- Only ASCII characters are allowed for data to be sent in the GET method. There is no such restriction in the POST method.
- GET is less secure compared to POST because the data sent is part of the URL. So, the GET method should not be used when sending passwords or other sensitive information.
GET and POST Requests Using Python
This post discusses two HTTP (Hypertext Transfer Protocol) request methods GET and POST requests in Python and their implementation in Python.