Sobes.tech
Junior — Middle

Have you ever had to configure or extend the functionality of FastAPI for specific requirements?

sobes.tech AI

Answer from AI

Yes, in FastAPI it is often necessary to customize or extend functionality for specific requirements. For example:

  • Adding custom middleware for logging or error handling.
  • Using Dependency Injection to connect services or databases.
  • Extending data validation with Pydantic models.
  • Configuring CORS, authentication, and authorization via OAuth2 or JWT.
  • Creating custom routes with parameters and handlers.

An example of adding middleware for logging request processing time:

from fastapi import FastAPI, Request
import time

app = FastAPI()

@app.middleware("http")
async def log_request_time(request: Request, call_next):
    start_time = time.time()
    response = await call_next(request)
    duration = time.time() - start_time
    print(f"Request {request.url.path} took {duration:.4f} seconds")
    return response

Thus, FastAPI provides flexible options for extension and customization for project tasks.