Home > Enterprise >  Not able to send a post request using a Python Script
Not able to send a post request using a Python Script

Time:01-05

I built my first API using FastAPI and after completing development and deployed my application using an Ubuntu server. I have also set-up NGINX & SSL.

I now need to populate my database with information that I already have available, and I figured that the best way to do so in bulk was through a python script (I will have more than 1000 records to post). During production, I had set up my script and it was working perfectly but now I can't get it to work in development. I've tried a hundred different ways but the post request gets redirected to a GET request and the response is a 200 OK message rather than a 201 created message. What's even more perplexing is that POST requests are working when done though Postman, and then when I use Postman to get the code snippet in python it does not work. enter image description here

This my app: https://github.com/andreasmalta1/football_data_api.git This is where the app is hosted: https://thefootballdata.com/api/teams/

This my script to send the POST request:

import requests
import json

login_url = "https://thefootballdata.com/api/login"
post_url = "https://thefootballdata.com/api/teams"

login_response = requests.post(login_url, data=login_payload)
access_token = login_response.json()["access_token"]

payload = json.dumps({
  "full_name": "Andreas Calleja",
  "name": "Andreas"
})

headers = {
  'Authorization': f"Bearer {access_token}",
  'Content-Type': 'application/json'
}

response = requests.request("POST", url=post_url, headers=headers, data=payload)

print(response.text)

CodePudding user response:

As pointed out by Chris, since my API allows both GET and POST requests at the same endpoint (api/teams), the solution was to put a trailing / at the request URL. Throughout my testing this was not needed in Postman and during development, but only during production scripting.

CodePudding user response:

you can post your data like this :

import requests
import json

login_url = "https://thefootballdata.com/api/login"
post_url = "https://thefootballdata.com/api/teams"

login_response = requests.post(login_url, data=login_payload)
access_token = login_response.json()["access_token"]

# post data 
post_payload = {
     "full_name": "Andreas Calleja",
     "name": "Andreas"
}

post_headers = { "Authorization": "Bearer "   access_token }

post_response = requests.post(post_url, data=post_payload, headers=post_headers)
print(post_response.json())
  • Related