DevNet Associate (DEVASC) v1.0Software Development and DesignMedium
A developer is creating a Python script to interact with a RESTful API. The API requires that the request body for creating a new resource be sent as a JSON string with a specific content type. Which of the following Python `requests` library methods automatically handles both the serialization of a Python dictionary to JSON and sets the `Content-Type: application/json` header?
- Arequests.post()
- Brequests.delete()
- Crequests.get()
- Drequests.put()
Show answer & explanationAnswer & explanation
Correct answer: A. requests.post()
The `requests.post()` and `requests.put()` methods specifically support sending JSON data. When the `json` parameter is used with `requests.post()`, it automatically serializes the Python dictionary to a JSON string and sets the `Content-Type` header to `application/json`.
Why the other options are wrong
- B. `requests.delete()` is used for removing resources and does not typically involve sending a JSON request body.
- C. `requests.get()` is used for retrieving data and does not typically send a request body in this manner.
- D. `requests.put()` also supports the `json` parameter for updating resources, but `post` is more common for creation as per the scenario.
requests.post() with JSON
The `requests.post()` method in Python is used to send POST requests, typically for creating new resources. When provided with the `json` parameter (a Python dictionary), it automatically serializes the dictionary into a JSON formatted string and sets the `Content-Type` header to `application/json`.
- Used for creating new resources on a server.
- Accepts a `json` parameter (Python dict) for automatic serialization.
- Automatically sets `Content-Type: application/json` header.
Memory trick: Python's 'requests' library makes web interactions both easy and robust, like ordering pizza online.