Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Requests POST not working

I am using python requests module for calling API's. Everything was working fine until I pushed my code to AWS. Even on AWS it is working if I am working on dev server i.e., ec2.####.amazon.com:8000 .

Here is my code :

r = requests.post(api_url, data = {"var 1":"value", "var 2":"value"})

My API url not allowed GET method so in response I am getting error that GET method not allowed which means requests.post is reads as get

Any idea what’s wrong here.

like image 261
user5594493 Avatar asked Dec 21 '15 12:12

user5594493


People also ask

How do you send a POST request in Python?

To create a POST request in Python, use the requests. post() method. The requests post() method accepts URL. data, json, and args as arguments and sends a POST request to a specified URL.

How do you send data in a request body in Python?

You'll want to adapt the data you send in the body of your request to the specified URL. Syntax: requests. post(url, data={key: value}, json={key: value}, headers={key:value}, args) *(data, json, headers parameters are optional.)

What is payload in Python request?

JSON Payload Example [Python Code] A request payload is data that clients send to the server in the body of an HTTP POST, PUT, or PATCH message that contains important information about the request.


1 Answers

Actually the issue was due to SSL , if your server is using https method then you need to add following line in requests.post

r = requests.post(api_url, data = {"var 1":"value", "var 2":"value"}, verify=True)

Also make sure your api_url includes https not http

I have written a small function for that

def get_base_url(request):
    host = get_host(request)
    if request.is_secure():
        return '{0}{1}/{2}'.format('https://', host, 'url')
    else:
        return '{0}{1}/{2}'.format('http://', host, 'url')
like image 166
user5594493 Avatar answered Sep 20 '22 23:09

user5594493