【问题标题】:Connecting to a rest API with python. How to setup headers & parameters?使用 python 连接到一个 REST API。如何设置标题和参数?
【发布时间】:2017-08-07 17:02:49
【问题描述】:

我正在使用 python 设置一个 rest api,但是我在让它工作时遇到了一些问题。

我正在使用 TV DB rest api:https://api.thetvdb.com/swagger

并使用带有 Requests 库的 python 来提取信息。

我的代码目前是:

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,不知道为什么。

已解决:

2 需要改变的地方 1、resp改成:

resp = requests.post(URL + "login/", headers = headers, data=json.dumps(params))
  1. 标题必须有

    "Content-Type": "application/json"
    

已添加 :) 现在可以使用了,谢谢大家

【问题讨论】:

    标签: python api python-requests


    【解决方案1】:

    登录参数可能需要是一个 JSON 编码的字符串,作为消息的正文发布。

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

    【讨论】:

    • 您也可以使用resp.raise_for_status() 代替 if/else 块来使代码更简洁。
    • 您也可以使用requests.post(..., json=params)requests 为您进行JSON 编码。
    • 这似乎做了一些不同的事情,但是,我现在收到错误 415,不知道为什么
    • 修复了!错误 415 已通过添加:Content-Type: application/json into header 得到修复
    • 你可能还需要标题Content-Type: application/json
    猜你喜欢
    • 2022-10-05
    • 1970-01-01
    • 2020-06-19
    • 1970-01-01
    • 1970-01-01
    • 2020-02-15
    • 2017-05-23
    • 1970-01-01
    • 2020-06-24
    相关资源
    最近更新 更多