IniziaInizia gratis

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.

Questo esercizio fa parte del corso

Introduction to APIs in Python

Visualizza il corso

Istruzioni dell'esercizio

  • 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.

Esercizio pratico interattivo

Prova a risolvere questo esercizio completando il codice di esempio.

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.____)
Modifica ed esegui il codice