Many web API frameworks contain a concept called “middleware” (but every language/framework calls it differently - filters, middleware, etc). Essentially, the middleware performs some specific function on the HTTP request or response before or after the handler. Common tasks to offload to a middleware would be logging, authorization, body compression, etc.

RestRserve comes with several build-in middlewares (AuthMiddleware, CORSMiddleware) and generic Middleware class which facilitates user to create a custom middleware.

Let’s see it in action in example below.


Let’s say you have a simple app which has only a single endpoint - it simply convert query string parameters into a JSON format and sends it back:

See it in action:

Assume you would like to analyze how your web service works. For that you may need log every request and response in order to see whether service replies with errors and what can cause these errors. This is a perfect task for a middleware and here is how you can achieve this with RestRserve:

Let’s test again:

Let’s see what will happen if we will send request to nonexistent endpoint:

Later you will see all the responses with errors in the log (status_code >= 400). Also you will be able to find corresponding requests by inspecting request_id field.

Middleware order

It is important to understand that middlewares are executed in order you’ve added them (that’s why it is called append_middleware). Flow is shown on the diagram below.


To demonstrate the order in which middleware called let’s consider another example.

Sometimes it it useful to compress response body in order to send less data over the wire. Here we will implement a middleware which will compress response with gzip.

And now check what is actual decoded response body: