2

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

1 Answer 1

3

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))

Sign up to request clarification or add additional context in comments.

7 Comments

also you can use resp.raise_for_status() instead of the if/else block to make for cleaner code.
You can also use the requests.post(..., json=params) to have requests do the JSON encoding for your.
This seems to have done something different, however, I am now getting error 415, not sure why
Fixed it! Error 415 was fixed by adding: Content-Type: application/json into header
You probably also need the header Content-Type: application/json
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.