Home > Net >  Is there a way to make a put request for changing an element within json array?
Is there a way to make a put request for changing an element within json array?

Time:06-18

Lets say I have this json:

{'name': 'jon',
 'id' : '20304',
 'pets': [{'name': 'sparkles',
           'age': 10
           'stats': {'weight':10,
                     'favetoy':'cottonball'
                     'color': 'green'}
          }]
}

Im trying to modify the 'color' parameter inside stats in a PUT request, by doing something like:

url = "https://....." #hostname api url
payload = {
        'pets': [{'stats:{'color':'red}}]           
}
response = requests.put(url, json=payload, headers=headers)
 #assume headers defined elsewhere.

And while it is changing the color to red, it's also changing the whole 'pets' array (name, age) to nothing, which makes sense, since my request body doesnt include anything for the other params within the array. But I just want to change the color to red, while keeping the rest the same...but I don't see how since its nested within the array... what would I include in the request body instead?

TLDR: I just want to make an api put request to modify 'color' and keep everything else the same in the same way you do with 'id' or 'name'.

Any ideas??

CodePudding user response:

treat payload as dictionary and make calls in that fashion, here the call will be like

payload["pets"][0]["stats"]["color"] = "red"#the changed color the [0] is there as there is alist

CodePudding user response:

According to REST principles, to transmit only the parameters you want to change you should use the method PATCH, not PUT.

PATCH is used to modify capabilities. The PATCH request only needs to contain the changes to the resource, not the complete resource.

This resembles PUT, but the body contains a set of instructions describing how a resource currently residing on the server should be modified to produce a new version. This means that the PATCH body should not just be a modified part of the resource, but in some kind of patch language like JSON Patch or XML Patch.

Whether it's actually possible to do that in your case depends on the api you are working with. If it supports PATCH, check the api documentation to find out how to use it.

Otherwise you're stuck with retrieving the entire object, making the changes you want, and using PUT to commit the modified version of the entire object.

  • Related