pythonrequestforge

Conditional variable in payload


I am a very beginner and struggling with a POST Request. I would like to have a conditional variable in payload which skips project services if they are not active in the project. To have a list of active services I called GET Projects and exported the list of projects to csv where projects names are rows and services are columns. Whenever service is active it has value 1 in its column. Is it possible to tailor services to payload if value in the csv is !=0?

start = "https://developer.api.autodesk.com/bim360/admin/v1/projects/"
end = "/users"

for i in range (len(projects_df)):
    payload = json.dumps({
                "email": "dummy@lalaland.com",

                "companyId": "0000",
                "roleIds": [
                  "0000"
                ],
                "services": [
                  {
                    "serviceName": "documentManagement",
                    "access": "administrator"
                  },
                  {
                    "serviceName": "projectAdministration",
                    "access": "administrator"
                  },
                  {
                    "serviceName": "projectManagement",
                    "access": "administrator"
                  },
                  {
                    "serviceName": "costManagement",
                    "access": "administrator"
                  },
                  {
                    "serviceName": "fieldManagement",
                    "access": "administrator"
                  },
                  {
                  "serviceName": "modelCoordination",
                  "access": "administrator"
                  },
                  {
                  "serviceName": "insight",
                  "access": "administrator"
                  }
                ]
              })
    
    headers = {
                        'Authorization': 'Bearer ' + access_token_beta,
                        'Content-Type': 'application/json',
                        'User-Id': 'XXXXX'
                        }

            

    project_id = projects_df.iloc[i,0]
    url = start+project_id+end

    response = requests.request("POST", url, headers=headers, data=payload)
    jsonAsPythonValue = json.loads(response.text)
    if (i == 0):
        post_user = pd.DataFrame.from_dict(pd.json_normalize(jsonAsPythonValue))  
    else:
        post_user = post_user.append(pd.DataFrame.from_dict(pd.json_normalize(jsonAsPythonValue)),ignore_index=True)

    i=i+1
   

Thank you in advance!


Solution

  • What I usually do is create payload with a minimal set of data, and then have a series of if conditions that add to it as necessary.

    payload = {
        'key1': 'value1',
        'key2': 'value2'
    }
    
    if condition1:
        payload['key3'] = 'value3'
    
    if condition2:
        payload['key4'] = 'value4'