pythonpython-3.xpython-requests

How do I make a variable in the requests payload for python?


I have the following payload for the requests module in python and I want to make MAC and NAME a variable as I iterate through a csv of information? Is there a way to do this?

  payload = '''{
        "clients": [
            {
                "mac": MAC,
                "name": NAME
            },
        ],}'''

Solution

  • Hand-formatting JSON is error-prone. For example, the trailing commas were incorrect and the curly braces need to be doubled up for a f-string.

    Instead, Use a Python object and serialize it with json.dumps:

    import json
    
    MAC = 'xxxxxxxxxxxx'
    NAME = 'example'
    
    payload = json.dumps({"clients": [{"mac": MAC, "name": NAME}]}, indent=2)
    
    print(payload)
    

    Output:

    {
      "clients": [
        {
          "mac": "xxxxxxxxxxxx",
          "name": "example"
        }
      ]
    }
    

    Also, depending on what you are doing, are you sure you need a JSON string? For example, a get can be:

    payload = {'key1': 'value1', 'key2': 'value2'}
    r = requests.get('https://httpbin.org/get', params=payload)
    

    or a put can be:

    r = requests.put('https://httpbin.org/put', data={'key': 'value'})