MulaiMulai sekarang secara 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.

Latihan ini adalah bagian dari kursus

Introduction to APIs in Python

Lihat Kursus

Petunjuk latihan

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

Latihan interaktif praktis

Cobalah latihan ini dengan menyelesaikan kode contoh berikut.

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 dan Jalankan Kode