Create middleware for specific route – Python

If you are creating an API in Python, and came across a problem where you have to create a middleware but for only specific route. For example, you are creating a user authentication system and want to create a middleware that checks if the user is logged-in. But you want to use that middleware for only few routes, not for all routes. Then this tutorial is for you.

This can be done by creating subapps in Python. To create a subapp in Python, first we need to create a file where we will save the global variable of our subapp.

Create a file, let’s say config.py, and write the following code in it.

# config.py

from fastapi import FastAPI

my_middleware_app = FastAPI()

Now create a file for our middleware, I am naming it my_middleware.py. Following will be the code of this file.

from fastapi import Request
from config import my_middleware_app

from fastapi.responses import JSONResponse
from fastapi.encoders import jsonable_encoder

@my_middleware_app.middleware("http")
async def my_func(request: Request, call_next):
	if "Authorization" in request.headers:
		print(request.headers["Authorization"])

		request.state.name = "Adnan"
		response = await call_next(request)
		return response
	else:
		return JSONResponse(content=jsonable_encoder("Authorization header not provided."))

Explanation:

  1. First, it imports the subapp “my_middleware_app” from “config” module.
  2. Then it imports “JSONResponse” and “jsonable_encoder” from “fastapi” modules. They will be required to send the response back to the client.
  3. Then we are creating a middleware using our subapp “my_middleware_app”.
  4. In this, we are checking if the request has “Authorization” header provided.
    • To learn more about authorization in Python, check our tutorial on user authentication.
  5. If not, then we are sending an error.
  6. If provided, then we are attaching a “name” variable with the request and pass it to the route.

Now let me show you, how the route can use this middleware and how route can access the “name” variable.

Following will be the content of our main.py file where the route will be created.

# main.py

from fastapi import FastAPI, Request
from config import my_middleware_app
import my_middleware

app = FastAPI()

@my_middleware_app.post("/my-route")
def my_route(request: Request):
	return request.state.name

app.mount("/", my_middleware_app)

We first imported the subapp module and the middleware.

Then we created an instance of FastAPI (the main app).

After that, we are creating a post route using our subapp. In this route, we are using the “name” variable we created in our middleware.

To send value from middleware to route, we can use request.state object.

And lastly, we are mounting the subapp to our main app.

Creating a middleware and using it just for specific route in Python is a bit confusing sometimes. So if you face any problem in following this, please do not hesitate to get in touch with me.

Custom middleware in Node JS

Middleware in Node JS is called before the request is handled by the router function. They stand between the router and the request. Middlewares are great when it comes to processing and validating request values before they reach the route.

Make sure you have downloaded and installed Node JS in your system first. You can download Node JS from here.

We are going to create a simple middleware that will add a new field “email” with the request.

# open terminal at desktop
# following command will create a folder
> mkdir nodejs-middleware

# open the folder in command prompt
> cd nodejs-middleware

# create a file named "server.js" in that folder
# following command will initialize the project
> npm init

# install express module
> npm install express

# start the server
> node server.js

Now in our server.js file, we will first start the server.

// server.js

// include express module
const express = require("express")

// create instance of express module
const app = express()

// get the port number if already set, or 3000 otherwise
const port = process.env.PORT || 3000

// start the server at specified port
app.listen(port)

// test in browser
// http://localhost:3000

Make sure to restart the server using “node server.js” command. Now we will create our custom middleware.

// create a custom middleware
const myMiddleware = function (request, result, next) {
	// add "email" field with the request object
  	request.email = "support@adnan-tech.com"
  
  	// continue with the request
	next()
}

The following code will add the middleware to all the requests.

// attach middleware to all requests
app.use(myMiddleware)

The following code will add the middleware to specific requests only.

// attach middleware to specific request
app.get("/", myMiddleware, function (request, result) {
	// display "email" value on browser
  	result.send(request.email)
})

Restart the server and check in your browser: http://localhost:3000

External middleware in Node JS

You can create your middleware in a separate file as well in your Node JS server. Create a file named “external-middleware.js” at the root of your project and write the following code in it:

module.exports = function (request, result, next) {
	request.email = "adnan@gmail.com"
	next()
}

Then in your “server.js” file, use the middleware like the following:

const externalMiddleware = require("./external-middleware")
app.use(externalMiddleware)

To test this middleware, remove or comment out the previous middleware and refresh your browser again. Check out our android application’s tutorial we created on Node JS.