FastAPI_Interview_QA_Full
FastAPI_Interview_QA_Full
Q: What is FastAPI? How does it differ from frameworks like Flask and Django?
A: FastAPI is a modern, high-performance web framework for building APIs with Python 3.7+ based
on standard type hints. It is faster than Flask and Django, supports asynchronous programming
(async/await), and automatically generates validation and interactive API docs.
A: Fast to run, automatic OpenAPI & JSON Schema generation, data validation with Pydantic,
dependency injection system, asynchronous programming support, and easy database integration.
A: Install using 'pip install fastapi uvicorn'. Define a FastAPI instance and routes, then run with
'uvicorn main:app --reload'.
A: Use route decorators like @app.get(), @app.post() above your function definitions.
A: By including them in function parameters - path parameters directly and query parameters as
optional with default values.
A: Use 'Form' and 'UploadFile' from fastapi, passing them as dependencies in your endpoint
functions.
A: It uses Pydantic models and Python type hints to perform automatic request validation and raise
errors if inputs are invalid.
A: A parameter to route decorators to specify the response schema using a Pydantic model.
A: FastAPI doesn't have built-in caching; use third-party libraries like 'FastAPI-Caching' or external
tools like Redis.
A: FastAPI uses 'Depends' to declare dependencies which can be automatically resolved and
injected into your routes.
A: Define a dependency function that yields the connection, and inject it into your routes using
'Depends'.
A: Use libraries like 'python-jose' or 'fastapi-jwt-auth' to encode, decode tokens and secure
endpoints via dependency injection.
A: Security schemes like OAuth2PasswordBearer are utilities that help define and secure
authentication flows.
Q: What is middleware?
A: Middleware is a function that runs before and/or after each request to handle cross-cutting
concerns.
Q: What is TestClient?
A: A testing utility that wraps your FastAPI app and lets you test it like an HTTP client.
A: Create an engine, session, and models. Manage DB sessions via dependency injection.
A: Define a 'get_db' function that yields a session and inject it using 'Depends'.
A: Use Uvicorn or Gunicorn with Uvicorn workers behind a reverse proxy like Nginx or deploy in
Docker.
Q: Difference between Uvicorn and Gunicorn?
A: Uvicorn is an ASGI server, Gunicorn is a WSGI server. Use Uvicorn workers inside Gunicorn for
async apps.
A: Proxy requests from Nginx to your Uvicorn server via reverse proxy configuration.
A: Use 'BackgroundTasks' from fastapi and add tasks with 'add_task' method.
Q: WebSockets example?
A: Add 'CORSMiddleware' to your FastAPI app with allowed origins, methods, and headers.
A: Use query parameters like 'limit' and 'offset' to control the number of returned results.