0
0
FastAPIframework~30 mins

Trusted host middleware in FastAPI - Mini Project: Build & Apply

Choose your learning style9 modes available
Trusted Host Middleware in FastAPI
📖 Scenario: You are building a simple web API using FastAPI. To keep your API safe, you want to allow requests only from certain trusted hosts, like your own domain and localhost.
🎯 Goal: Build a FastAPI app that uses the TrustedHostMiddleware to accept requests only from example.com and localhost.
📋 What You'll Learn
Create a FastAPI app instance
Add TrustedHostMiddleware with allowed hosts example.com and localhost
Create a simple root endpoint that returns a welcome message
Run the app so it enforces trusted hosts
💡 Why This Matters
🌍 Real World
TrustedHostMiddleware helps protect your API by allowing requests only from known, safe domains. This prevents some types of attacks and misuse.
💼 Career
Understanding middleware and security features like trusted hosts is important for backend developers building secure web APIs.
Progress0 / 4 steps
1
Create a FastAPI app instance
Import FastAPI from fastapi and create an app instance called app.
FastAPI
Need a hint?

Use from fastapi import FastAPI and then app = FastAPI().

2
Add TrustedHostMiddleware with allowed hosts
Import TrustedHostMiddleware from fastapi.middleware.trustedhost and add it to app with allowed_hosts set to ["example.com", "localhost"].
FastAPI
Need a hint?

Use app.add_middleware(TrustedHostMiddleware, allowed_hosts=["example.com", "localhost"]).

3
Create a root endpoint
Define a GET endpoint at "/" on app that returns a JSON message {"message": "Welcome to the trusted host API!"}.
FastAPI
Need a hint?

Use @app.get("/") decorator and define an async function root that returns the message.

4
Run the FastAPI app
Add the code to run the app with uvicorn when the script is executed directly. Use uvicorn.run(app, host="0.0.0.0", port=8000) inside if __name__ == "__main__".
FastAPI
Need a hint?

Import uvicorn and use if __name__ == "__main__" to run the app.