简体   繁体   中英

Connecting to a rest API with python. How to setup headers & parameters?

i'm working on settin up a rest api with python, however i'm having some problem getting it to work.

I'm working with the TV DB rest api: https://api.thetvdb.com/swagger

and using python with Requests library to pull out the information.

My code is currently:

import json 
import requests

 URL = "https://api.thetvdb.com/"

API_KEY = "Api_key"
USER_KEY = "Key"
USERNAME = "Name"

headers  = {"Accept": "application/json"}
params = {
  "apikey": API_KEY,
  "userkey": USER_KEY,
  "username": USERNAME
}

resp = requests.post(URL + "login/", headers = headers ,params=params)

if resp.status_code != 200:
    print('error: ' + str(resp.status_code))
else:
    print('Success')

So far i'm only getting error code 401, not sure why.

Solved:

2 Things needed to be changed 1. The resp was changed into:

resp = requests.post(URL + "login/", headers = headers, data=json.dumps(params))
  1. The header had to have

     "Content-Type": "application/json" 

added to it :) It's now working, thanks everyone

The login parameters probably need to be a JSON-encoded string POSTed as the body of the message.

Try resp = requests.post(URL + "login/", headers = headers, data=json.dumps(params))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM