Get startedGet started for free

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.

This exercise is part of the course

Introduction to APIs in Python

View Course

Exercise instructions

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

Hands-on interactive exercise

Have a go at this exercise by completing this sample code.

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.____)
Edit and Run Code