Home > Software engineering >  Convert CURL API command to Python API using requests and json
Convert CURL API command to Python API using requests and json

Time:02-06

I am connecting through an API to receive data. From the website API documentation, the instructions use either two CURL methods to connect the API; however, I need to connect using python.

1st Method Curl Example

curl -d '' -X POST 'https://api.bcda.cms.gov/auth/token' \
    -H "accept: application/json" \
    -H "authorization: Basic <Client_Secret>"

My Python Conversion:

import requests
import json

url = 'https://api.bcda.cms.gov/auth/token'
       headers = {"accept": "application/json", "authorization": 'Basic',
            '<API_Key>': '<API_Secret>'}

r = requests.post(url = url, data ={}, headers = headers)
   print(r)

2nd Method Curl

curl -d '' -X POST 'https://api.bcda.cms.gov/auth/token' \
    --user <Client_Key>:<Client_Secret> \
    -H "accept: application/json"


My 2nd Python conversion code:

import requests
import json

url = 'https://api.bcda.cms.gov/auth/token'

user = {"<Client_Key>":"<Client_Secret>", "accept": "application/json"}

r = requests.post(url = url, headers = user)

print(r)

I am receiving a 403 connection error, meaning "response status code indicates that the server understands the request but refuses to authorize it."

CodePudding user response:

You should use auth parameter and not headers to convert --user option

headers = {'accept': 'application/json'}
r = requests.post(url=url, headers=headers, auth=(client_key, client_secret))
  •  Tags:  
  • Related