Synchronous calls

As we've seen in the previous chapters, synchronous interactions between microservices can be done via RESTful HTTP APIs using JSON payloads.

That's by far the most used pattern, because both HTTP and JSON are the golden standards. If your web service implements an HTTP API that accepts JSON, any developer using any programming language will happily use it.

Following a RESTful scheme, on the other hand, is not a requirement and is prone to interpretation. Countless blog posts are debating the virtue of using POST versus PUT response on the internet.

Some projects implement Remote Procedure Call (RPC) APIs over HTTP rather than REST APIs. In RPC, the focus is on the action, which is part of the endpoint URL. In REST, the focus is on the resource, and actions are defined by HTTP methods.

Some projects are a mix of both and don't strictly follow a given standard. The most important thing is that your service behavior should be consistent and well-documented.

This book leans on REST rather than RPC, but is not strict about it, and does not have a strong opinion about all the PUT versus POST debates.

Sending and receiving JSON payloads is the simplest way for a microservice to interact with the others, and only requires microservices to know the entry points and parameters to pass using HTTP requests.

To do this, you just need to use an HTTP client. Python has one built-in in the http.client module, but the Requests library (https://docs.python-requests.org) has a better API to work with and offers built-in features that will make your life easier.

HTTP requests in the requests library are built around the concept of session, and the best way to use it is to create a Session object that is reused every time you interact with any service.

A Session object can hold, among other things, authentication information and some default headers you want to set for all requests your application will make. In the following example, the Session object will automatically create the right Authorization and Content-Type headers:

    from requests import Session 

s = Session()
s.headers['Content-Type'] = 'application/json'
s.auth = 'tarek', 'password'

# doing some calls, auth and headers are all set!
s.get('http://localhost:5000/api').json()
s.get('http://localhost:5000/api2').json()

Let's see how we can generalize this pattern in a Flask app that needs to interact with other services.

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

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