I am trying to use patebin api from python using requests.post which sends out a post request, my code is
# 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 = "my api key"
# 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)
The curl post request as given in the documentation works for my api key and I got the paste url.
But I am getting Bad API request, use POST request, not GET output for the above python code does anyone has any suggetions
The simple fix, as @LeventeKovács points out, is to change the request type in your URL from "http" to "https". Here's why the Requests library doesn't do what you want/expect with your current URL...
You are doing a HTTP request to a HTTPS endpoint. This requires a redirect from HTTP to HTTPS. When handling this redirect, the Requests library changes the POST to a GET, with this code:
# Second, if a POST is responded to with a 301, turn it into a GET.
# This bizarre behaviour is explained in Issue 1704.
if response.status_code == codes.moved and method == 'POST':
method = 'GET'
Here's a link the the issue mentioned in the comment associated this code:
That issue cites this part of the HTTP spec:
301 Moved Permanently If the 301 status code is received in response to a request other than GET or HEAD, the user agent MUST NOT automatically redirect the request unless it can be confirmed by the user, since this might change the conditions under which the request was issued. Note: When automatically redirecting a POST request after receiving a 301 status code, some existing HTTP/1.0 user agents will erroneously change it into a GET request.
and then seems to go on to rationalize the code's behavior by saying that the Requests library should do what most/all browsers currently do, which is to change the POST to a GET and retry at the new address.