0
0
FastAPIframework~30 mins

Protected routes in FastAPI - Mini Project: Build & Apply

Choose your learning style9 modes available
Protected Routes with FastAPI
📖 Scenario: You are building a simple web API using FastAPI. Some parts of your API should only be accessible to users who provide a secret token. This is like having a locked door that only opens if you have the right key.
🎯 Goal: Create a FastAPI app with one public route and one protected route. The protected route should only allow access if the request includes the correct secret token in the headers.
📋 What You'll Learn
Create a FastAPI app instance named app
Define a secret token string variable named SECRET_TOKEN with value "mysecrettoken"
Create a public route at /public that returns a welcome message
Create a protected route at /protected that checks for the header X-Token
If the X-Token header matches SECRET_TOKEN, return a success message
If the token is missing or incorrect, return a 401 Unauthorized error
💡 Why This Matters
🌍 Real World
Many web APIs need to protect certain routes so only authorized users can access them. This project shows a simple way to do that with FastAPI.
💼 Career
Understanding how to protect routes is essential for backend developers building secure APIs. This skill is commonly required in real-world web development jobs.
Progress0 / 4 steps
1
Create FastAPI app and secret token
Import FastAPI from fastapi. Create a FastAPI app instance called app. Then create a string variable called SECRET_TOKEN and set it to "mysecrettoken".
FastAPI
Need a hint?

Remember to import FastAPI first. Then create the app and the secret token variable exactly as named.

2
Create a public route
Add a route to app using the decorator @app.get("/public"). Define a function called public_route that returns a dictionary with the key message and value "Welcome to the public route!".
FastAPI
Need a hint?

Use the @app.get decorator with the path /public. The function should return the exact dictionary.

3
Add header parameter and check token
Import Header and HTTPException from fastapi. Create a route at /protected with @app.get("/protected"). Define a function called protected_route that takes a parameter x_token with type str | None and default Header(default=None, alias="X-Token"). Inside the function, check if x_token is not equal to SECRET_TOKEN. If so, raise HTTPException(status_code=401, detail="Unauthorized").
FastAPI
Need a hint?

Use Header to read the X-Token header. Compare it to SECRET_TOKEN and raise HTTPException if it does not match.

4
Return success message from protected route
In the protected_route function, after the token check, return a dictionary with the key message and value "You have access to the protected route!".
FastAPI
Need a hint?

Return the success message dictionary after the token check passes.