Home > Net >  Problem passing dictionary to API via requests.post()
Problem passing dictionary to API via requests.post()

Time:11-30

As noted below, I am trying to pass the dictionary data to the API.

def create_flow_and_phases(request):

    data = {
        "name": "name_example",
        "description":"description_example",
        "category": 2,
        "precedents": [2,3],
        "users": [1],
        "phases": [{
                "name": "phase_name",
                "description": "description name",
                "sequence_number": 1,
                "precedents": [1]
            }]
    }

    # Making a POST request to save flow_and_phases
    url = API_HOST   "/api/flows/save_flow_and_phases/"

    answer = requests.post(url, data=data, headers={'Authorization': 'Token '   request.session['user_token']})

    if not answer.ok:
        raise Exception("An error occurred while creating flow.")

Below, you can see that the dictionary data format is the same one passed in Insomnia to the API and that it works perfectly.

{
  "name": "Testando criação de fluxo pelo Insomnia",
  "description": "Fluxo teste simulando informações de trato e colheita de café na fazendo fictícia Quipo",
  "category": 2,
  "precedents": [2, 3],
    "users": [1],
    "phases": [
         {
            "name": "Trato anual",
            "description": "Descrição teste fase 1.",
            "sequence_number": 1,
            "precedents": []
         },
        {
            "name": "Trato anual 2",
            "description": "Descrição teste fase 2.",
            "sequence_number": 2,
            "precedents": [1]
         }
    ]
}

The backend receives data as below

flow_data = dict(data) # data is passed as parameter

But when I go to run the debub, the data referring to phases are not passed to the API as shown in the screenshot below

enter image description here

As shown in the image, the list with phases is not being passed. What's happening? Any suggestion?

CodePudding user response:

Post the data as JSON, nested data does not work as regular POST data. You can pass the data in the json parameter and requests should handle the headers and serialisation for you

answer = requests.post(url, json=data, headers={'Authorization': 'Token '   request.session['user_token']})
  • Related