28

I've got a really simple question, but I can't figure it out how to do it. The problem I have is that I want to send the following payload using Python and Requests:

{ 'on': true }

Doing it like this:

payload = { 'on':true }
r = requests.put("http://192.168.2.196/api/newdeveloper/lights/1/state", data = payload)

Doesn't work, because I get the following error:

NameError: name 'true' is not defined

Sending the true as 'true' is not accepted by my server, so that's not an option. Anyone a suggestion? Thanks!

Erik Pragt
  • 13,513
  • 11
  • 58
  • 64
  • 4
    `True` on python is spelt with a capital 'T' :) – GP89 Jul 31 '13 at 20:35
  • 2
    Uhm, it's `True` in Python... –  Jul 31 '13 at 20:35
  • 3
    I know that it's True. But when I put 'True' there, the payload will be "{'on': True}". I want it to be "{'on': true}" – Erik Pragt Jul 31 '13 at 20:40
  • 1
    You need to json encode it to get it to a string. `import json` `payload = json.dumps({"on":True})` – GP89 Jul 31 '13 at 20:41
  • can boolean data be send over GET params? I tried using python-requests, but Other side I am receiving string data. I want to pass some some boolean (true/false) data. – OmPrakash Sep 19 '17 at 14:45
  • 2
    @OmPrakash GET data has to be a string yes, it's just part of the URL. if you are using json you can just use `json.loads(data)` to convert it back on the server, or whichever appropriate deserialisation. – GP89 Jun 06 '18 at 07:39

4 Answers4

31

You need to json encode it to get it to a string.

import json 
payload = json.dumps({"on":True})
GP89
  • 6,600
  • 4
  • 36
  • 64
6

Starting from requests 2.4.2, instead of passing in the payload with the data parameter, you can use the json parameter like this:

payload = {'on': True}
requests.put(url, json=payload)

And the request will be formatted correctly as a json payload (i.e. {'on': true}).

Jack
  • 5,354
  • 2
  • 29
  • 54
5

should be {'on': True}, capital T

Conan Li
  • 474
  • 2
  • 6
1

to make it be lower case like that (if that's what your endpoint requires) do in quotes {'on':'true'}

Matt N
  • 867
  • 7
  • 6