使用python连接到restapi。如何设置标题和参数?

2024-05-21 08:14:59 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在用python建立restapi,但是在让它正常工作时遇到了一些问题。在

我正在使用tvbrestapi:https://api.thetvdb.com/swagger

并使用python和Requests库提取信息。在

我的代码当前为:

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

到目前为止,我只得到错误代码401,不知道为什么。在

已解决:

有两件事需要改变 1resp改为:

^{pr2}$
  1. 头球必须有

    "Content-Type": "application/json"
    

添加到它:)它现在工作了,谢谢大家


Tags: keyhttpsimportcomapijsonurlusername