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

463 Views Asked by At

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.

So far I got this Curl command:

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.

But I don't know how to code this in 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.

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

3

There are 3 best solutions below

0
Preetham On BEST ANSWER

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)
0
RoadRunner On

Try using requests.post() to perform a HTTP POST request to your REST API:

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)
0
mr_m1m3 On

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