Search code examples
pythonjsondockerpython-requestsurllib

Python Requests. POSTing JSON NameError for boolean


I'm trying to POST JSON content to an API using Python and requests but I'm getting a NameError because my JSON contains a boolean.

I've tried with urllib3 and just requests and both display the same behaviour.

"enabled": true,
NameError: name 'true' is not defined

I'm building in docker:

FROM python:slim

ADD script.py requirements.txt ./

RUN pip install -r requirements.txt

# Run app.py when the container launches
CMD ["python", "script.py"]

requirements.txt

requests==v2.23.0
urllib3==1.25.8

script.py

#import urllib3
import json

resp = req.post('https://example.com/api/endPoint',
  json={
      "name": "myName",
      "rules": [{
        "type": "foo",
        "enabled": true}]
  })

Solution

  • As @andreis mentioned try using boolean True in below snippet. In python boolean true is written as True

    #import urllib3
    import json
    
    resp = req.post('https://example.com/api/endPoint',
      json={
          "name": "myName",
          "rules": [{
            "type": "foo",
            "enabled": True}]  # from true to True
      })
    

    https://docs.python.org/3/library/functions.html?highlight=bool#bool