Aan de slagGa gratis aan de slag

Sending JSON with the requests package

Similar to how you can receive JSON text from an API response, you can also send JSON text to an API with POST or PUT requests. If you use the json argument for the request.post() and request.put() methods, the requests library will take care of adding all the necessary headers and encoding for you. Neat!

Let's try it out! Did you know you can create multiple playlists at once using a POST request to the /playlists API? Just pass an array of playlists (each with a Name property) to the API and it will create them all at once.

Deze oefening maakt deel uit van de cursus

Introduction to APIs in Python

Cursus bekijken

Oefeninstructies

  • Pass the playlists variable as an argument to the requests.post() method so that it will be automatically sent as JSON.
  • Get a list of all playlists from the API.
  • Inspect the response of the GET request by printing the JSON text.

Praktische interactieve oefening

Probeer deze oefening eens door deze voorbeeldcode in te vullen.

playlists = [{"Name":"Rock ballads"}, {"Name":"My favorite songs"}, {"Name":"Road Trip"}]

# POST the playlists array to the API using the json argument
requests.post('http://localhost:3000/playlists/', ____=____)

# Get the list of all created playlists
response = requests.____('http://localhost:3000/playlists')

# Print the response text to inspect the JSON text
print(response.____)
Code bewerken en uitvoeren