Home > Enterprise >  Using REST EPA in Python code gives an error What is wrong with this code?
Using REST EPA in Python code gives an error What is wrong with this code?

Time:04-21

REST API document

---------------------------------------------------------------
curl --location --request POST 'https://zaya.io/api/v1/links' \
--header 'Content-Type: application/x-www-form-urlencoded' \
--header 'Authorization: Bearer {api_key}' \
--data-urlencode 'url={url}'
-----------------------------------------------------------------

My Code

import requests
api="https://zaya.io/api/v1/links"
API_KEY = "################################################"
data = "https://en.wikipedia.org/wiki/Python_(programming_language)"
headers = {'Authorization': 'Bearer '   API_KEY}
r = requests.get(api, data=data, headers=headers)
print(response.text)

The error I face:

{"message":"You are not logged in.","status":403} 

CodePudding user response:

  • Mistake 1 You are doing a GET where the document asks you to send a POST.
  • Mistake 2 The data must be form URL encoded, must be key-value pairs
  • Mistake 3 You must set the proper Content-Type header
  • Bigger mistake Do not post your API key on public forums.

The code below works fine, with the above corrections.

import requests

api = "https://zaya.io/api/v1/links"

# Never reveal your API key
API_KEY = "##########################################################"

# Data is URL Form encoded, so it must be key-value pair
data = {"url": "https://en.wikipedia.org/wiki/Python_(programming_language)"}

# Add proper headers
headers = {'Authorization': 'Bearer '   API_KEY, 'Content-Type': 'application/x-www-form-urlencoded'}

# Most important. CURL says POST, you did GET 
r = requests.post(api, data=data, headers=headers)
print(r.text)
# Gives proper response
  • Related