FastAPI Interview Questions 1-5 (Introduction, Core Features, Comparison)

Welcome to the world of FastAPI! If you are applying for modern Python backend roles, this is the framework everyone is talking about. In this lesson, we will cover the foundational concepts that set FastAPI apart from older frameworks.

We will explore why it is considered one of the fastest Python frameworks, how it leverages modern Python features like type hints, and understand the underlying architecture (ASGI) that makes it all possible. These are the "must-know" questions to prove you understand the tool, not just how to copy-paste code.

1. What is FastAPI and why is it popular?

FastAPI is a modern, fast (high-performance) web framework for building APIs with Python 3.8+, based on standard Python type hints. It was created by Sebastián Ramírez and released in 2018.

It has gained immense popularity because it solves the "slow" reputation of Python web frameworks. It is built on top of two key libraries: Starlette (for the web parts) and Pydantic (for the data parts).

Why is it popular?

  • Speed: It is on par with NodeJS and Go (thanks to Starlette and ASGI).
  • Developer Experience: It provides great editor support (autocompletion) and catches bugs before you even run the code.
  • Standards-based: It uses open standards for APIs (OpenAPI/Swagger) and data (JSON Schema).

Here is the simplest "Hello World" in FastAPI. Notice how clean it looks.

from fastapi import FastAPI

# 1. Create the app instance
app = FastAPI()

# 2. Define a path operation (route)
@app.get("/")
def read_root():
    return {"message": "Hello World"}

# To run this, you would use a terminal command:
# uvicorn main:app --reload

Sample Output (JSON response):

{
  "message": "Hello World"
}

2. What are the key features of FastAPI?

If an interviewer asks this, they want to know if you understand why you would choose FastAPI over Flask. Focus on the "Big Three": Performance, Documentation, and Validation.

  • 1. Automatic Interactive Documentation:
    Without writing a single line of extra code, FastAPI generates a dynamic Swagger UI page (at /docs) that lets you test your API directly in the browser.
  • 2. Data Validation (Pydantic):
    It automatically validates incoming data types. If a user sends a string instead of an integer, FastAPI returns a clear error message automatically.
  • 3. Async/Await Support:
    It supports asynchronous programming natively, making it perfect for tasks that wait for databases or external APIs.

Here is an example of Data Validation in action. We define a data "shape" using a class, and FastAPI enforces it.

from fastapi import FastAPI
from pydantic import BaseModel

app = FastAPI()

# Define the shape of data we expect
class Item(BaseModel):
    name: str
    price: float
    is_offer: bool = None

@app.post("/items/")
def create_item(item: Item):
    # Because we used type hints (item: Item), FastAPI:
    # 1. Reads the JSON body
    # 2. Converts types (if needed)
    # 3. Validates the data
    return {"item_name": item.name, "item_price": item.price}

3. How does FastAPI compare with Flask and Django REST Framework?

This is a classic system design or architectural question. There is no "best" framework, only the right tool for the job.

Analogy:
- Django is a fully furnished house. It has everything (kitchen, bed, TV), but it's hard to move the walls.
- Flask is a box of tools (hammer, nails). You build the house yourself. It gives you freedom but requires more work.
- FastAPI is a modern prefab home kit using the latest technology (robots/automation). It builds itself quickly and is very efficient, but it's newer.

FeatureDjango (DRF)FlaskFastAPI
PhilosophyBatteries Included (Full Stack)Microframework (Minimalist)Modern Microframework (Performance)
PerformanceSlower (Sync)Slower (Sync)Very Fast (Async / ASGI)
Learning CurveSteep (Lots to learn)Easy (Good for beginners)Moderate (Need to know Types/Async)
ValidationDjango Forms / SerializersExtensions (Marshmallow)Native (Pydantic)

4. What is ASGI and how is it different from WSGI?

To understand FastAPI's speed, you must understand ASGI. Historically, Python web apps used WSGI (Web Server Gateway Interface).

  • WSGI (Synchronous): Used by Flask and Django (classically). Imagine a phone call. When you call the server, the server stays on the line with you until the request is finished. It can't handle another call on that specific line while waiting.
  • ASGI (Asynchronous): Used by FastAPI. Imagine texting. You send a message (request). The server reads it, starts working, and can read other people's texts while waiting for the database to reply. It handles thousands of "conversations" at once.

Technical Note: You cannot run an ASGI app with standard WSGI servers like Gunicorn directly. You need an ASGI server like Uvicorn or Hypercorn.

# Typical command to run a FastAPI app
# 'main' is the file name (main.py)
# 'app' is the FastAPI object instance inside that file

uvicorn main:app --host 0.0.0.0 --port 8000

5. Explain how FastAPI uses Python type hints.

This is the "secret sauce" of FastAPI. In standard Python, type hints (like : str or : int) are usually ignored by the computer; they are just comments for developers.

FastAPI creates value from them.It uses the standard type hints to do three things simultaneously:

  • 1. Validation: Checks if the data matches the type.
  • 2. Serialization: Converts data (e.g., JSON to Python objects).
  • 3. Documentation: Updates the Swagger UI to tell API users what type is expected.

Note: This means you define your API specifications using Python syntax, not a separate configuration file. Code is the documentation.

Look at this function. Because we added : int and : str, FastAPI knows exactly what to do.

from typing import Optional

@app.get("/items/{item_id}")
def read_item(item_id: int, q: Optional[str] = None):
    return {"item_id": item_id, "q": q}

# Scenario 1: User visits /items/5
# Output: {"item_id": 5, "q": None}
# (FastAPI converts "5" from the URL string to an integer automatically)

# Scenario 2: User visits /items/foo
# Output: Error!
# (FastAPI sees "foo" is not an int, and returns a helpful validation error)

Without FastAPI, you would have to write manual code to check if is_digit(item_id)and convert it. FastAPI does this for you essentially for free.

🚀 Deep Dive With AI Scholar