2

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.

1
  • 1
    Please do use a more useful title for your questions. Commented Sep 4, 2013 at 9:06

2 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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'}]}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.