Python Microservices, Part 2: Build and Test REST endpoints with Tornado
At Slang Labs, we are building a platform for programmers to easily and quickly add multilingual, multimodal Voice Augmented eXperiences (VAX) to their mobile and web apps. Think of an assistant like Alexa or Siri, but running inside your app and tailored for your app.
The platform is powered by a collection of microservices. For implementing these services, we chose Tornado because it has AsyncIO APIs. It is not heavyweight. Yet, it is mature and has a number of configurations, hooks, and a nice testing framework.
This blog post covers some of the best practices we learned while building these services; how to:
- Design REST endpoints as a separate layer over business logic,
- Implement Tornado HTTP server and service endpoint handlers,
- Use Tornado hooks to control behavior and assist debugging, and
- Write unit and integration tests using Tornado testing infra.
Application REST Endpoints
As an example, we will build a CRUD microservice for an address-book using Tornado:
- Create an address: POST /addresses
Returns HTTP status 201 upon adding successfully, and 400 if request body payload is malformed. The request body should have the new address entry in JSON format. The id the newly created address is sent back in the Location attribute of the header of the HTTP response. - Read an address: GET /addresses/{id}
Returns 404 if the id doesn’t exist, else returns 200. The response body contains the address in JSON format. - Update an address: PUT /addresses/{id}
Returns 204 upon updating successfully, 404 if the request body is malformed, and 404 if the id doesn’t exist. The request body should have the new value of the address. - Delete an address: DELETE /addresses/{id}
Returns 204 upon deleting the address, 404 is id doesn’t exist. - List all addresses: GET /addresses
Returns 200, and the response body with all addresses in the address book.
In case of an error (i.e. when return status code is 4xx or 5xx), the response body has JSON describing the error.
You may want to refer to the list of HTTP status codes, and best practices for REST API design.
By the end of this blog post, you will know how to implement and test these endpoints.
Get Source Code
Clone the GitHub repo and inspect the content:
The service endpoints and tests are implemented in the highlighted files in the listing above.
Setup a virtual environment, and install the dependencies from requirements.txt. Run tests as a sanity check.
Layered Design
The address service will be implemented in two layers:
- Service Layer contains all the business logic and knows nothing about REST and HTTP.
- Web Framework Layer contains REST service endpoints over HTTP protocol and knows nothing about business logic.

The Service Layer exposes the function APIs for various CRUD operations to be used by the Web Framework layer.
Since the focus of this article is on the Web Framework layer, the Service layer is implemented as simple stubs.
In the AddressBookService class uses an in-memory dictionary to store the addresses. In reality, it will a lot more complicated, and using some databases. Nonetheless, it is functioning. It is enough for implementing and testing the Web Framework layer.
Tornado Web Framework
Tornado is a Python web framework with asyncio APIs (if needed, please review asyncio cooperative multitasking concepts).
For implementing a service, you need to define following in Tornado:
- Request Handlers for endpoint methods,
- Application routing configuration mapping all request handlers to regex for endpoints,
- HTTP Server that listens on a given port and routes requests to the application.
Request Handlers
A request handler is needed for every endpoint regex. For address-book service, there are two handlers needed:
- AddressBookRequestHandler for /addresses/: GET and POST methods for creating a new entry and listing all entries respectively,
- AddressBookEntryRequestHandler for /addresses/{id}: GET, PUT, and DELETE methods for reading, updating, and deleting a specific entry respectively.
Both of these inherit from BaseRequestHandler that has common functionalities. For example, Tornado returns HTTP response by default, but the address-book service must return JSON.
The BaseRequestHandler utilizes the following Tornado hooks:
- write_error method: to send a JSON error message instead of HTTP,
- serve_traceback setting: to send exception traceback in debug mode,
- initialize method: to get the needed objects (like the underlying AddressBookService that has the business logic).
You will see how initialize and serve_traceback are tied to the handlers in the next section.
These handlers define a set of valid endpoint URLs. A default handler can be defined to handle all invalid URLs. The prepare method is called for all HTTP methods.
Application Routing Configuration
All request handlers need to be tied into a tornado.web.Application. That requires the following:
- RegEx-handler mapping: A list of a tuple (regex, handler class, parameters to handler’s initialize method) that is how the service object is passed to all handlers,
- Settings: e.g., serve_traceback, default_handler_class.
The make_addrservice_app function creates an AddressBookService object, uses it to make tornado.web.Application, and then returns both the service and app.
In the debug mode, serve_traceback is set True. When an exception happens, the error returned to the client also has the exception string. We have found this very useful in debugging. Without requiring to scan through server logs and to attach a debugger to the server, the exception string at the client offers good pointers to the cause.
HTTP Server
The application (that has routes to various request handlers) is started as an HTTP server with following steps:
- Start AddressBook (business logic) service
- Create an HTTP server (app.listen)
- Start asyncio event loop (loop.run_forever)
When the server is stopped, the server is stopped and all pending requests are completed:
- Stop asyncio event loop (loop.stop)
- Stop HTTP server (http_server.stop)
- Complete all pending requests (loop.shutdown_asyncgens)
- Stop AddressBook service
- Close the event loop (loop.close)
The proof of the pudding
Let’s run the server and try some requests.
Run the server
Test default handler
There is no /xyz endpoint, so it returns 404:
Create an address entry
Add an address entry, the returned location is the id to query later:
Read the address entry
Use the id in the Location field in the previous request to query it:
Update the address entry
Let’s change the name:
List all addresses
Delete the address
Verify address is deleted
Tornado Testing Framework
Manual testing is tedious and error-prone. Tornado provides testing infrastructure. It starts the HTTP server and runs the tests. It does necessary plumbing to route the HTTP requests to the server it started.
Test classes should inherit from AsyncHTTPTestCase, and implement a get_app method, which returns the tornado.web.Application. It is similar to what is done in server.py. Code duplication can be kept at a minimum by reusing make_addrservice_app function in get_app.
Tornado creates a new IOLoop for each test. When it is not appropriate to use a new loop, you should override get_new_ioloop method.
Unit Test Cases
For address book service, except default handler, all handlers use the service (business logic) module. That module has only simple stubs in this blog post, but in reality, it will be way more complex. So only default handler is independent and qualifies for the unit tests. All other handlers should be covered in the integration tests (next section).
Integration Test Cases
The whole life cycle of an address entry tested manually earlier can be automated as integration tests. It will be a lot easier and faster to run all those tests in seconds every time you make a code change.
Code Coverage
Let’s run these tests:
Let’s check code coverage:
As you can see, it is pretty good coverage.
Notice that addrservice/tornado/server.py was omitted from code coverage. It has the code that runs the HTTP server, but Tornado test infra has its own mechanism of running the HTTP server. This is the only file that can not be covered by unit and integration tests. Including it will skew the overall coverage metrics.
Summary
In this article, you learned about how to put together a microservice and tests using Tornado:
- Layered design: Isolate endpoint code in Web Framework Layer, and implement business logic in Service Layer.
- Tornado: Implement the web framework layer with Tornado request handlers, app endpoint routing, and HTTP server.
- Tests: Write unit and integration tests for the web framework layer using Tornado testing infrastructure.
- Tooling: Use lint, test, code coverage for measuring the health of the code. Integrate early, write stub code if necessary to make it run end-to-end.
