简体   繁体   English

我需要帮助将此REST API Curl命令转换为Python请求

[英]I need help converting this REST API Curl command to Python requests

I'm new around here, and rather new to all that is coding to be honest. 我在这里是新手,老实说对所有编码都是新手。

I'm trying to create a Pyton script to search for items from a Request Tracker asset database using REST API. 我正在尝试创建一个Pyton脚本,以使用REST API从Request Tracker资产数据库中搜索项目。

So far I got this Curl command: 到目前为止,我得到了以下Curl命令:

curl    -X POST \
-H "Content-Type: application/json" \
-d '[{ "field" : "Owner", "operator" : "LIKE", "value" : "NAME" },{"field":"Catalog", "value":"1"}]' \
-H 'Authorization: token MY_TOKEN' \
'https://RT_URL/rt/REST/2.0/assets'

It returns a nice JSON with results from RT_URL where Owner is matching NAME using token MY_TOKEN. 它会返回一个不错的JSON,其结果来自RT_URL,其中所有者使用令牌MY_TOKEN匹配NAME。

But I don't know how to code this in Python. 但是我不知道如何用Python编写代码。 I have a script that use the requests library to fetch is using a simple URL request, but I can't figure out how to implement the search fields. 我有一个使用请求库来获取的脚本正在使用一个简单的URL请求,但是我不知道如何实现搜索字段。

I've looked all over to find a sample, but I can't get it to work. 我到处寻找样本,但是无法正常工作。 I haven't found any info on how to authenticate in requests using a token. 我尚未找到有关如何在使用令牌的请求中进行身份验证的任何信息。

Anyway, thanks in advance for any respons :) 无论如何,在此先感谢您的答复:)

Try using requests.post() to perform a HTTP POST request to your REST API: 尝试使用requests.post()对您的REST API执行HTTP POST请求:

import requests
import json

# URL
url = 'https://RT_URL/rt/REST/2.0/assets'

# JSON data 
data = '[{ "field" : "Owner", "operator" : "LIKE", "value" : "NAME" },{"field":"Catalog", "value":"1"}]'

# Request headers
headers = {"Content-Type": "application/json", "Authorization": "token MY_TOKEN"}

# POST request
requests.post(url=url, data=data, headers=headers)

Try this code 试试这个代码

import requests

headers = {
    'Content-Type': 'application/json',
    'Authorization': 'token TOKEN',
}

data = '[{ "field" : "value"}] ......'

response = requests.post('YOUR_URL', headers=headers, data=data)

First let's build headers dict for your request: 首先让我们为您的请求构建标头字典:

headers = {
    'Content-Type': 'application/json', (...)
}

then, let's create your body: 然后,让我们创建您的身体:

json = [{
        "field": "Owner",
        "operator": "LIKE",
        "value": "NAME"
    }, {
        "field": "Catalog",
        "value": "1"
    }]

Finally, let's POST your request: 最后,让我们发布您的请求:

response = requests.post('https://RT_URL/rt/REST/2.0/assets', json=json, headers=headers)

This should do the trick. 这应该可以解决问题。

You can find more info here 您可以在这里找到更多信息

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

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