Django Bot
Django Bot

Reputation: 319

Nested GET parameters for a HTTP API

I was trying to use python-requests to use a certain API.

I have tried:

import requests
data = ?
r = requests.get('http://localhost:8777/v2/meters/instance', params=data)

The query that I would like to build is as below:

http://localhost:8777/v2/meters/instance?q.field=project_id&q.value=s56464dsf6343466

My problem is, How may I able to pass q.field=project_id&q.value=s56464dsf6343466

I tried like this but it doesn't work

data = { 'q': [{'field':'project_id', 'value': 's56464dsf6343466'}] }

I hope someone could help.

Upvotes: 2

Views: 6134

Answers (2)

reubano
reubano

Reputation: 5353

You have to encode the data first, like this:

from requests import get
from urllib import urlencode

url = 'http://localhost:8777/v2/meters/instance'
data = {'q': [{'field':'project_id', 'value': 's56464dsf6343466'}]}
get(url, params=urlencode(data), headers=HDR)

And then you decode it like this:

from ast import literal_eval

@route('/v2/meters/instance')
def meters():
    kwargs = request.args.to_dict()
    # kwargs is {'q': "[{'field':'project_id', 'value': 's56464dsf6343466'}]"}
    kwargs = {k: literal_eval(v) for k, v in kwargs.iteritems()}
    # kwargs is now {'q': [{'field':'project_id', 'value': 's56464dsf6343466'}]}

Upvotes: 0

Martijn Pieters
Martijn Pieters

Reputation: 1121148

You'll have to name each parameter explicitly:

data = {'q.field':'project_id', 'q.value': 's56464dsf6343466'}

There is no standard for marshalling more complex structures into GET query parameters; the only standard that exists gives you key-value pairs. As such, the requests library doesn't support anything else.

You can of course write your own marshaller, one that takes nested dictionaries or lists and generates a flat dictionary or tuple of key-value pairs for you.

Upvotes: 4

Related Questions