Implementing a REST client

Before looking at a smarter REST server application, we'll look at writing a REST client. The standard library has two packages useful for creating a client: http.client and urllib. These packages both provide features required to make RESTful requests over HTTP. Both packages include features to create requests with bodies, include headers, add complex URLs and retrieve a result, save the result headers, save any attachments, and track the status code. A popular alternative to urllib is the requests package. For further information, check out http://docs.python-requests.org/en/master/.

You can get the Open API specification with the following simple code:

import requests
get_openapi = requests.get(
"http://127.0.0.1:5000/openapi.json")
if get_openapi.status_code == 200:
document = get_openapi.json()

This will make an HTTP GET request to the given URI. The response object, get_openapi, will be examined and a few useful fields extracted. The value of get_openapi.status_code is the HTTP status code returned from the server. The get_openapi.json() method will attempt to read and parse the body of the response. If it is valid JSON, the resulting Python object can be examined further. In the case of Open API specifications, the object will be a Python dictionary. For these examples, we'd expect document['info']['version'] != '2019.02'. Any other result indicates a potential problem between the client and server.

In the next section, we'll unit test the RESTful services.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset