DevNet Associate (DEVASC) v1.0Software Development and DesignMedium
A developer needs to create a Python script that interacts with a network device's REST API. The API requires sending JSON data in the request body and expects JSON data in return. Which Python library and its function would be most suitable for handling both sending and receiving JSON data in HTTP requests?
- Arequests.get() with json.dumps() and json.loads()
- Bhttp.client.HTTPConnection() with manual header and body encoding/decoding
- Crequests.post() with the 'json' parameter for sending and .json() method for receiving
- Durllib.request.urlopen() with json.dumps() and json.loads()
Show answer & explanationAnswer & explanation
Correct answer: C. requests.post() with the 'json' parameter for sending and .json() method for receiving
The `requests` library is the de facto standard for HTTP requests in Python. Its `post()` method has a convenient `json` parameter for sending JSON data, and the response object's `.json()` method automatically decodes JSON responses, simplifying the process significantly.
Why the other options are wrong
- A. `requests.get()` is for GET requests; POST is needed for sending data in the body. While `json.dumps()` and `json.loads()` are correct for serialization, `requests.post()` is more appropriate.
- B. `http.client` is a low-level library, requiring significant manual effort for headers, body encoding, and response decoding, making it less suitable for common use cases.
- D. `urllib.request` is built-in but more verbose; `json.dumps()` and `json.loads()` are correct for encoding/decoding, but `urlopen()` requires manual handling of headers and body encoding.
Python Requests Library
The Requests library is a popular, elegant, and simple HTTP library for Python, designed to simplify making HTTP requests. It handles many complexities automatically, such as connection pooling, SSL verification, and JSON encoding/decoding.
- Simplifies HTTP requests (GET, POST, PUT, DELETE)
- Automatic JSON serialization/deserialization
- Handles headers, parameters, authentication
- Not built-in, needs installation (`pip install requests`)
Memory trick: Requests 'asks' and 'receives' JSON with ease, like a polite server.