如何在python3中发布这个API代码和请求模块?一直到405

2024-05-29 04:39:23 发布

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

我想用一个链接缩短器网站的API。我知道给定的例子是在curl中,-H表示有一个标题,PUT表示它正在发布,但无论我怎么尝试,似乎都无法得到我想要的结果。我能做的就是要么得到一个405错误,要么打破它。在

我在安装了python3的Windows上,并且已经安装了requests。在

For developers Shorte.st prepared API which returns responses in JSON format.

Currently there is one method which can be used to shorten links on behalf of your account.

Take a look on the sample below to learn how to use our API.

curl -H "public-api-token: (my token)" -X PUT -d
"urlToShorten=google.com" https://api.shorte.st/v1/data/url 

When received,

{"status":"ok","shortenedUrl":"http:\/\/sh.st\/XXXX"}

我试过几件事

import requests
import json
gogo = { 'public-api-token: (my token)' : 'urlToShorten=google.com'}
yep = requests.post('https://api.shorte.st/v1/data/url',   
data=json.dumps(gogo))
print (yep.text)

显示一个错误405的HTML网页。在

^{pr2}$

还显示了一个错误405的网页。在

我现在知道了-H是用于页眉的,我在使用它的同时,仍然可以得到页面。在

import requests
import json

headers = { 'public-api-token' : '(my token)' }
gogo = {"urlToShorten" : "google.com"}
yep = requests.post('https://api.shorte.st/v1/data/url',  
data=json.dumps(gogo), headers=headers)
print (yep.text)

又一次尝试了405次

gogo = {"public-api-token: (my token)" : "urlToShorten=google.com"}
yep = requests.post('https://api.shorte.st/v1/data/url', 
data=json.dumps(gogo))
print (yep.text)

即使这样,如果我去掉文本,也只会给我一个完整的html页面/405。在

headers = { "public-api-token: (my token)" : "urlToShorten=google.com" }
yep = requests.post('https://api.shorte.st/v1/data/url', headers=headers)
print (yep.text)

Tags: httpscomtokenapidatamygooglepublic
1条回答
网友
1楼 · 发布于 2024-05-29 04:39:23

您正在将PUT有效负载放入头中。把它放在身体里。您的有效负载是而不是JSON,因此不需要尝试将其视为JSON。在

头需要指定为字典,头名称和令牌作为键和值。有效载荷的参数可以用同样的方式处理。在

您还使用了错误的requests方法;要发送PUT请求,请改用^{} function

headers = {'public-api-token': '(my token)'}
payload = {'urlToShorten': 'google.com'}
response = requests.put(
    'https://api.shorte.st/v1/data/url',
    data=payload, headers=headers)

print(response.json())

response对象有一个^{} method来解码API返回的JSON数据;它将为您提供与JSON文本相对应的Python数据结构。在

我没有您正在使用的服务的令牌;我使用^{} service创建了一个演示;它反映了作为JSON响应发送的内容:

^{pr2}$

如果将其与curl向同一个URL发送PUT请求所产生的输出进行比较,您将看到相同的结果:

$ curl -H "public-api-token: (my token)" -X PUT \
     -d "urlToShorten=google.com" http://httpbin.org/put
{
  "args": {}, 
  "data": "", 
  "files": {}, 
  "form": {
    "urlToShorten": "google.com"
  }, 
  "headers": {
    "Accept": "*/*", 
    "Content-Length": "23", 
    "Content-Type": "application/x-www-form-urlencoded", 
    "Host": "httpbin.org", 
    "Public-Api-Token": "(my token)", 
    "User-Agent": "curl/7.37.1"
  }, 
  "json": null, 
  "origin": "94.118.96.0", 
  "url": "http://httpbin.org/put"
}

相关问题 更多 >

    热门问题