Pratyusha M
Pratyusha M

Reputation: 33

add params to url in python

I would like to pass two parameters to my url(status code & parent id). The json response of the url request is such :

{
"page": 1,
"per_page": 10,
"total": 35,
"total_pages": 4,
"data": [
       {
        "id": 11,
        "timestamp": 1565193225660,
        "status": "RUNNING",
        "operatingParams": {
            "rotorSpeed": 2363,
            "slack": 63.07,
            "rootThreshold": 0
        },
        "asset": {
            "id": 4,
            "alias": "Secondary Rotor"
        },
        "parent": {
            "id": 2,
            "alias": "Main Rotor Shaft"
        }
    }]

I would like to know how to pass the two parameters in the url. Passing ?status=RUNNING gives the response of all the devices which have running as status (thats pretty straightforward). For now I have tried this:

import requests
resp = requests.get('https://jsonmock.hackerrank.com/api/iot_devices/search?status=RUNNING')
q = resp.json()
print(q)

How should I pass in parentid=2, so it returns a response with devices which have their parent id=2.Thank you.

Upvotes: 0

Views: 1348

Answers (3)

hitesh kumar
hitesh kumar

Reputation: 491

If you want to send data via get request the process is straight forward note how different values are seperated with '&'.

url?name1=value1&name2=value2

If you are using Flask for backend then you can access these parameters like.

para1=request.args.get("name1")
para2=request.args.get("name2")

On the front end you can use ajax to send the request

var xhttp=new XMLHttpRequest();
var url="url?name1=value1&name2=value2"
xhttp.open("GET",url,true)
xhttp.onreadystatechange = function() {
  if (this.readyState == 4 && this.status == 200) 
  {
    console.log(this.responseText);
  }
};
xhttp.send();

Upvotes: 0

Paul Bombarde
Paul Bombarde

Reputation: 311

To add a second get parameter, use the & separator :

import requests
resp = requests.get('https://jsonmock.hackerrank.com/api/iot_devices/search?status=RUNNING&parentid=2')
q = resp.json()
print(q)

Upvotes: 0

AKX
AKX

Reputation: 168824

It's plainly documented under "Passing Parameters in URLs" in the Requests docs.

resp = requests.get(
    'https://jsonmock.hackerrank.com/api/iot_devices/search',
    params={
        'status': 'RUNNING',
        'parentid': 2,
    },
)

Upvotes: 2

Related Questions