简体   繁体   English

将 httpie post 请求转换为 python 请求库

[英]Convert httpie post request to python requests library

I have difficulties converting a post request using htppie to python requests.post.我很难将使用 htppie 的发布请求转换为 python requests.post。 This question is in general about how to do such a conversion, but I will use the specific request I was doing as an example.这个问题一般是关于如何进行这样的转换,但我会以我正在做的具体请求为例。

So I have the following post request using httpie, which works fine:所以我有以下使用httpie的post请求,它工作正常:

http post https://api.thegraph.com/subgraphs/name/graphprotocol/graph-network-mainnet query='{ indexers {
                id
               }
}'

However, when trying to send the same request using pythons requests library, I tried the following:但是,当尝试使用 pythons requests 库发送相同的请求时,我尝试了以下操作:

import requests

url = 'https://api.thegraph.com/subgraphs/name/graphprotocol/graph-network-mainnet'

query = """'{ indexers {
                id
                }
}'"""

print(requests.post(url, data = query).text)

This gives a server error (I tried many versions of this, as well as sending a dictionary for the data variable, and they all give the same error).这会导致服务器错误(我尝试了许多版本,以及为数据变量发送字典,它们都给出了相同的错误)。 The server error was GraphQL server error (client error): expected value at line 1 column 1 .服务器错误为GraphQL server error (client error): expected value at line 1 column 1

Regardless of what the server error is (which is probably server specific), this at least means that the two requests obviously are not exactly the same.不管服务器错误是什么(可能是特定于服务器的),这至少意味着这两个请求显然不完全相同。

So how would I go about converting this httpie request to using pythons requests library (or any other python library for that matter)?那么我将如何 go 将这个 httpie 请求转换为使用 pythons 请求库(或任何其他 python 库)?

To pass request payload, you need pass json as string (I used json.dumps() for conversion).要传递请求有效负载,您需要将 json 作为字符串传递(我使用json.dumps()进行转换)。 To pass body as form-data, pass just dict.要将正文作为表单数据传递,只需传递 dict。

import json
import requests

url = 'https://api.thegraph.com/subgraphs/name/graphprotocol/graph-network-mainnet'

payload=json.dumps({'query': '{indexers {id}}'})
headers = {
  'Content-Type': 'application/json',
}

response = requests.post(url, headers=headers, data=payload)

Note.笔记。 I recommend that you try to make this request in Postman and then you can convert the code to Python right in Postman.我建议您尝试在 Postman 中提出此请求,然后您可以在 Postman 中将代码转换为 Python。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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