FastAPI fundamentals

Follow one request, GET /students, from a phone to the RP Academy API and back: what an API is, how HTTP carries the message, what REST means, and how seven lines of FastAPI become a running server with its own documentation.

Animated diagram: a code panel on the left and, on the right, twelve pictures in turn: a waiter between a customer and a kitchen as a picture of an API, three clients and one server, the parts of an HTTP request and response, the same message readable over HTTP and locked over HTTPS, REST verbs acting on a table of six students, the FastAPI stack of Uvicorn, Starlette and Pydantic, installing into a virtual environment, the first application, running it with automatic reload, the life of one request, the generated OpenAPI documentation with Swagger UI and ReDoc, and FastAPI compared with Flask and Django
1

Before you start: the story, the project and the sample data

One project runs through all 15 FastAPI pages: RP Academy API. This first page writes its first lines. Read this section once: every later page uses the same names and the same numbers.

In the storyWhat it is
RP AcademyA small training institute in Hyderabad with 3 courses and, today, 6 students. Until now the front desk kept everything in one Excel sheet.
What it wantsA mobile app where a student sees the course and the fee paid, and an admin page for the office. Both need the same data, so the first thing to build is a backend that both can ask: an API.
Who builds itThe trainer gives the job to the "FastAPI Backend" batch as its course project. Asha writes the code on her laptop. Kiran, from the same batch, also helps at the front desk and will be the admin user of the finished system. You do everything Asha does.
The projectFolder rp_academy/, file main.py, application object app. It grows on every page: validation, a MySQL database, login with JWT, tests, Docker and AWS.
On this pageThe data is a Python list inside main.py with 4 columns (id, name, city, course_id). The API can only read. It has 3 routes: GET /, GET /health and GET /students.
The addresshttp://127.0.0.1:8000: your own computer, port 8000. A public address comes with deployment in Category 12.

These are the students and courses of the whole course. Later pages use all the columns. This page uses the first three and course_id.

idnameemailcitycourse_idfee_paidis_activejoined_on
1Ashaasha@rp.inHyderabad26000true2026-08-03
2Raviravi@rp.inChennai14000true2026-08-10
3Meenameena@rp.inPune34500true2026-09-01
4Kirankiran@rp.inWarangal26000true2026-09-07
5Farhanfarhan@rp.inBengaluru39000false2026-09-15
6Divyadivya@rp.inHyderabad10true2026-10-05
Course idtitlefeelevel
1Python Basics4000beginner
2FastAPI Backend6000intermediate
3AWS Data Engineering9000advanced

Numbers to remember: 6 students, 5 active, 2 in Hyderabad, β‚Ή29,500 paid in total. Meena still owes β‚Ή4,500 and Divya β‚Ή4,000. Whenever a later page adds a student, it is Suresh from Nellore, course 2, who becomes id 7.

The road of the course: Categories 1 to 4 build the endpoints and check the requests. Categories 5 to 8 add dependency injection, the database, login and middleware. Categories 9 to 11 cover async code, project structure and tests. Categories 12 to 14 deploy the API, connect it to AWS and make it fast and safe. Category 15 is complete projects.

rp_academy/        the project folder at the end of this page
  .venv/           the virtual environment (step 7). Never edit it, never put it in Git
  main.py          the application: 3 routes and the 6 students (steps 8 to 11)
  report.py        a small client program that calls the API (step 2)

How to read the code and the outputs: everything on this page was really run, on Linux, in the folder /home/asha/rp_academy, with Python 3.13, FastAPI 0.143.0, Starlette 1.7.0, Pydantic 2.14.0 and Uvicorn 0.54.0. Every output is the real output, shortened only where you see .... Dates, process ids in [ ] and client port numbers will differ on your machine. You need Python 3.10 or newer, a terminal, an editor such as VS Code, and a browser. curl is a small command-line client that is already on Windows 10 and 11 (type curl.exe in PowerShell), macOS and Linux.

Step-by-step notes

The same 12 steps as the animation. Press "Play this step" on a card to watch that step again.

1

🍽️ What is an API?

In simple words

A program is rarely alone. The RP Academy mobile app shows students, but the list of students does not live in the phone. It lives on a computer at the institute. The app needs a way to ask that computer: "give me the students". An API is that way. API means Application Programming Interface: a fixed, published list of requests that one program accepts from other programs, together with the answers it promises to give.

The waiter picture has three roles. The customer wants something but may not enter the kitchen. The kitchen can cook but does not talk to customers. The waiter stands between them. He accepts only orders that are on the menu, and he brings back a plate or a polite "we do not have that". In software the customer is the client (the app), the kitchen is the server (the code and the data), and the waiter is the API. The menu is the API documentation.

Why not let the app read the data directly? There are three reasons.

  • Safety. The app gets only what the API hands out. It can ask for a student's course. It can never read the whole table, the passwords or another student's fee.
  • Freedom to change. The kitchen may change from an Excel sheet to a Python list to MySQL. As long as the menu stays the same, no app has to change.
  • Reuse. The mobile app, the admin page and a nightly report all use the same API. A rule such as "an inactive student cannot enroll" is written once, on the server.

🎬 In the animation: in the top row a blue order slip, "1 masala dosa", travels from the customer through the waiter to the kitchen, and a green plate comes back. In the bottom row the same thing happens in software: the blue request GET /students travels from the client through the API to the server, and the green answer "200 · 6 students" comes back. On this whole page blue means a request, green a successful answer, orange a mistake of the client, and purple data. The kitchen and the server have dashed borders because the client never sees inside. The code panel shows the menu of our API.

Real-time scenario

Asha opens the RP Academy app on her phone to check her course. The app does not know the answer. It asks the API, the API reads the data and answers "Asha, Hyderabad, course 2". When the institute moves from a Python list to MySQL in Category 6, her app is not touched. You use APIs all day in the same way: a UPI app calls the API of your bank, a cab app calls a maps API, a weather app calls a weather API.

Code

This is the menu of RP Academy API at the end of this page, ordered with curl. You build the server that gives these answers in steps 7 to 9. For now, read the answers as a customer reads a menu.

curl http://127.0.0.1:8000/
curl http://127.0.0.1:8000/health
curl http://127.0.0.1:8000/teachers       # not on the menu

Output

{"message":"Welcome to RP Academy API"}
{"status":"ok"}
{"detail":"Not Found"}

Common mistake

Watch out: "API" does not mean "website" and it does not mean "database". A website answers people with pages (HTML). An API answers programs with data, almost always JSON. The word is also wider than the web: the functions of a Python library are an API too. On this page API always means a web API, called over HTTP.

2

πŸ–₯️ Client-server architecture

In simple words

"Architecture" only means how the parts are arranged. Here there are two roles. The client is the program that starts the conversation: it sends a request. The server is a program that runs all the time, waits on an address, and sends one response to each request. The server never speaks first.

The words describe roles, not machines. Your laptop is a client when it opens a website, and it is a server while fastapi dev runs on it. While you learn, the client and the server are the same laptop. The address tells the client where the server is, and it has four parts.

Part of http://127.0.0.1:8000/studentsNameMeaning
http://schemeHow to talk: the HTTP protocol (step 3). https:// is the locked version (step 4).
127.0.0.1hostWhich computer. This special IP address always means "this computer". Its name is localhost. In production it is a name such as api.example.com.
:8000portWhich program on that computer. A computer can run many servers, and each one takes a port number, like a flat number in an apartment building.
/studentspathWhat you want from that program.

This split is useful. The app team can redesign every screen without touching the server. The server team can change the database without touching the app. And clients of very different kinds can share one server, because they only need to agree on the messages.

🎬 In the animation: three clients stand on the left: a browser, the mobile app and a Python script. One after the other, each sends a blue GET /students along the grey wire into the server, and a green "200 · 6 students" travels back to the same client. Inside the server box you see the three layers that later steps open: Uvicorn (the web server program), the FastAPI app (your code) and the data, drawn as 6 purple dots, one per student. The counter at the end says 3 requests in, 3 answers out.

Real-time scenario

Monday, 10 am. Kiran opens the admin page in Chrome at the front desk. Asha opens the mobile app in the metro. At night report.py runs on the office computer and counts the students. Three programs, written in JavaScript, Kotlin and Python, and one server. None of them knows that the server is written in Python. They share only two things: HTTP for the conversation and JSON for the data.

Code

A client does not have to be an app with screens. This one is 8 lines of Python. httpx is a library for sending HTTP requests, and it was installed together with FastAPI.

# report.py: a client written in Python
import httpx

URL = "http://127.0.0.1:8000/students"
response = httpx.get(URL)
print(response.status_code)

students = response.json()     # JSON text -> list
first = students[0]["name"]
print(len(students), "students, first:", first)

Output of python report.py, while the server of step 9 is running

200
6 students, first: Asha

Common mistake

Watch out: a client can only get an answer while the server is running. If you close the terminal of the server, or never started it, the last line of the error is httpx.ConnectError: [Errno 111] Connection refused, and curl says Failed to connect to 127.0.0.1 port 8000. Nothing is wrong with your code: nobody is listening on that port. Start the server in one terminal and run the client in a second one.

3

βœ‰οΈ HTTP: the request and the response

In simple words

HTTP means HyperText Transfer Protocol. A protocol is an agreed format, like the fixed layout of a bank cheque: both sides know where each piece of information is written. HTTP says who speaks first (the client) and what a message looks like. Every HTTP message is plain text with three parts.

PartIn a requestIn a response
1. First lineGET /students HTTP/1.1: the method (what to do), the path (to which thing) and the version.HTTP/1.1 200 OK: the version, the status code (a number for programs) and a reason phrase (a word for people).
2. HeadersExtra facts, one name: value per line. Host: which server. User-Agent: which program asks. Accept: which formats the client can read.content-type: the format of the body. content-length: its size in bytes. server: which program answered.
3. BodyAfter one empty line. Empty for GET. POST and PUT carry their data here (Category 3).After one empty line. The data: here the 6 students, 334 bytes of JSON.

The status code is the fastest way to know what happened. The first digit gives the family.

FamilyMeaningCodes our API really returned on this page
2xxSuccess.200 OK for every route that exists.
3xxLook at another address.307 Temporary Redirect for /students/ with a slash at the end. FastAPI points the client to /students.
4xxThe client asked wrongly. Fix the request.404 Not Found for /teachers, 405 Method Not Allowed for a POST to /students, 422 Unprocessable Content for /students/abc in step 6.
5xxThe server failed. Fix the server code.500 Internal Server Error for the route with a bug in step 10.

JSON (JavaScript Object Notation) is the text format of the body. It has objects in { }, lists in [ ], text in double quotes, numbers, true, false and null. It looks like a Python dict, but it is only text, so every programming language can read it.

🎬 In the animation: the code panel shows the real conversation as curl -v prints it: lines with > were sent by the client, lines with < came from the server. On the right the same two messages are cut into their parts, one after the other: the request line with its three pills (method, path, version), the headers, the empty body; then the status line with the green 200, the four response headers and the purple body. The strip at the bottom shows the five families of status codes.

Real-time scenario

Kiran says: "the admin page shows nothing". Asha does not open her code first. She runs curl -i and reads the status line. 200 with an empty list: the data is the problem. 404: the page calls a wrong address. 500: her code crashed, and the terminal of the server shows where. No answer at all: the server is not running. Reading the status line first is the first habit of a backend developer.

Code

curl -v http://127.0.0.1:8000/students

Output (the body is one long line, shortened here)

> GET /students HTTP/1.1
> Host: 127.0.0.1:8000
> User-Agent: curl/8.5.0
> Accept: */*
>
< HTTP/1.1 200 OK
< date: Sun, 11 Oct 2026 17:37:20 GMT
< server: uvicorn
< content-length: 334
< content-type: application/json
<
[{"id":1,"name":"Asha","city":"Hyderabad","course_id":2},{"id":2,"name":"Ravi", ...

Python turns a dict into JSON text and back with the json module. FastAPI does this for you on every response. Look at what changes on the way: False becomes false and None becomes null.

import json

row = {"id": 5, "name": "Farhan", "is_active": False, "email": None}

text = json.dumps(row)          # Python dict -> JSON text
print(text)
print(type(text).__name__, len(text), "characters")

back = json.loads(text)         # JSON text -> Python dict
print(back["name"], back["is_active"], back["email"])

Output

{"id": 5, "name": "Farhan", "is_active": false, "email": null}
str 62 characters
Farhan False None

Test it yourself: open http://127.0.0.1:8000/students in a browser, press F12, choose the Network tab and reload. Click the request: the browser shows the same request headers, the status 200 and the response headers that curl printed.

Common mistake

Watch out: do not mix up who is at fault. 4xx means the request is wrong: fix the client or the address. 5xx means the server code is wrong: fix the server. Beginners see the word "error" and start changing server code for a 404 that was only a typing mistake in the URL.

4

πŸ”’ HTTP and HTTPS

In simple words

Plain HTTP sends its text exactly as you saw it in step 3. Every device on the way can read it: the Wi-Fi router of a cafe, another laptop on the same Wi-Fi, the internet provider. HTTPS is the same HTTP message, sent through a locked tunnel. The lock is called TLS (Transport Layer Security). Its older name, SSL, is still used in conversation and in option names.

TLS gives three things.

  • Privacy (encryption). Before any data is sent, client and server do a short "handshake" and agree on a secret key. After that the path, the headers and the body travel as bytes that only the two of them can open.
  • Identity (a certificate). The server shows a certificate, a file that says "I really am this address", signed by a trusted organisation called a certificate authority. The client checks it before it sends anything.
  • Integrity. If somebody changes a single byte on the way, the receiver notices and drops the message.

When an address names no port, http:// means port 80 and https:// means port 443. Port 8000 is only a habit for development. On your own laptop http://127.0.0.1:8000 is fine, because the message never leaves the computer. In production you normally do not give the certificate to Uvicorn. A load balancer or a proxy such as Nginx stands in front, speaks HTTPS with the world and passes plain HTTP to Uvicorn inside the private network (Categories 12 and 13).

🎬 In the animation: the top lane is HTTP. The blue request and the green answer cross the wire, and the card of the stranger fills with what he reads: the request line, the host and the names of the students. Both ends carry a red "no lock" label. The bottom lane is HTTPS. First a teal "TLS handshake" pill goes across and back, and a teal key appears at both ends. Then the same request and answer travel as "πŸ”’ 17 03 03 ...", and the stranger's card shows only those bytes. They are the real first bytes of our capture, which is in the code panel.

Real-time scenario

Category 7 adds login. The app will send Asha's e-mail address and password to /auth/login. Over plain HTTP in a cafe, anybody with a free packet reader could copy the password in seconds. Over HTTPS they see locked bytes. This is why browsers write "Not secure" next to http addresses and why app stores insist on HTTPS.

Code

We did not want you to take this on trust. We started the server of this page twice, once plain and once with a test certificate (key.pem and cert.pem, made with openssl for this test only), called it with curl, and let a small packet reader print what crossed the wire. You do not have to repeat this. Just compare the two outputs.

uvicorn main:app
curl http://127.0.0.1:8000/students

What the packet reader saw: plain HTTP

--- client -> server, 85 bytes
GET /students HTTP/1.1
Host: 127.0.0.1:8000
User-Agent: curl/8.5.0
Accept: */*
--- server -> client, 126 bytes
HTTP/1.1 200 OK
date: Sun, 11 Oct 2026 17:37:49 GMT
server: uvicorn
content-length: 334
content-type: application/json
--- server -> client, 334 bytes
[{"id":1,"name":"Asha","city":"Hyderabad","course_id":2},{"id":2,"name":"Ravi", ...
uvicorn main:app --ssl-keyfile key.pem --ssl-certfile cert.pem
curl --cacert cert.pem https://127.0.0.1:8000/students

What the packet reader saw: HTTPS (the request, then the body of the answer)

--- client -> server, 107 bytes
17 03 03 00 66 6d 52 ce d6 00 b8 2d 96 a3 f2 36 bb ac b6 c9 8d ec 22 26 ...
readable text in it: '....fmR....-...6......"&gx.6.&.h.b.8`.....9 ..T.'
--- server -> client, 356 bytes
17 03 03 01 5f aa cf 8b be 6e 50 75 10 c4 18 9b 94 8b 79 a7 46 27 05 da ...

The same request is 85 bytes in the clear and 107 bytes locked, and not one word of it can be read. curl itself still received the 6 students, because it holds the key. Two more real lines from this test show the identity check. curl with -v reported SSL connection using TLSv1.3 and SSL certificate verify ok. And when we did not tell curl to trust our home-made certificate, it refused to talk at all:

curl: (60) SSL certificate problem: self-signed certificate

Common mistake

Watch out: HTTPS protects the message on the way. It does not decide who may call your API. An open route is still open to everybody, only now through a locked tunnel. Deciding who the caller is and what the caller may do is authentication and authorization (Category 7). You need both.

5

🧱 REST API fundamentals

In simple words

REST means Representational State Transfer. The name comes from a doctoral thesis written in 2000. It is not a library and not a protocol. It is a style: a set of habits for designing HTTP APIs, so that every API feels familiar. An API that follows the habits is called RESTful.

  • Things have addresses. Everything the API manages is a resource: a student, a course. The path names it with a plural noun. /students is the whole collection and /students/3 is one student.
  • The method is the verb. You do not put the action in the path. The HTTP method carries it (table below).
  • Every request stands alone. The server keeps no memory of your earlier requests. This is called stateless. Each request carries everything needed, for example who is asking (a token in a header, Category 7). The benefit: any copy of the server can answer any request, so you can run ten copies behind a load balancer.
  • The data travels as a representation. The student in the database and the JSON you receive are not the same thing. The JSON is a representation of the student. That is the "representational" in the name.
  • Status codes tell the result, as in step 3.
#RequestMeaningUsual success codeRows touched in the picture
1GET /studentsRead the whole list200 OKAll 6
2GET /students/3Read one student200 OKMeena
3POST /studentsAdd a student. The new data is in the body201 CreatedA new row: Suresh, id 7
4PUT /students/3Replace the whole student. PATCH changes only the fields you send200 OKMeena
5DELETE /students/5Remove a student204 No ContentFarhan

On this page RP Academy API has only request 1. The table is the grammar. Category 2 builds the other four.

🎬 In the animation: the table on the left is the resource "students" with its 6 rows. On the right the five requests appear one by one, each with a blue method pill and the green status code it would normally return. A numbered badge lands on the rows that the request touches, and the rows blink: badge 1 on the header (all rows), 2 and 4 on Meena, 5 on Farhan. For request 3 an orange dashed row appears under the table: Suresh, the row a POST would add. The table itself still has 6 rows.

Real-time scenario

The developer of the mobile app has never seen RP Academy API. Because it is RESTful, she can guess most of it: the list is GET /students, one student is GET /students/3, a new student is a POST to /students. Asha has to explain almost nothing. Compare that with an API whose addresses are /getAllStudents, /student_delete?id=5 and /addNewStudentV2.

Code

Path and method together choose the action. Our API shows it already: the same path gives two different answers for two methods. -i makes curl print the status line and the headers, and -X sets the method.

curl -i http://127.0.0.1:8000/students
curl -i -X POST http://127.0.0.1:8000/students
curl -i http://127.0.0.1:8000/teachers

Output (the first answer is shortened to its status line)

HTTP/1.1 200 OK
...
HTTP/1.1 405 Method Not Allowed
date: Sun, 11 Oct 2026 17:37:21 GMT
server: uvicorn
allow: GET
content-length: 31
content-type: application/json

{"detail":"Method Not Allowed"}
HTTP/1.1 404 Not Found
date: Sun, 11 Oct 2026 17:37:21 GMT
server: uvicorn
content-length: 22
content-type: application/json

{"detail":"Not Found"}

Read the difference. 405: the address exists, but not with this method, and the header allow: GET tells the client what would work. 404: there is nothing at this address. FastAPI produced both answers by itself. We wrote no code for them.

Common mistake

Watch out: do not put verbs in the path (/getStudents, /deleteStudent/5), and never change data with GET. Browsers, caches and search engines repeat GET requests freely because GET is supposed to be safe. An address like GET /students/5/delete will one day delete a student because somebody's browser loaded the link in advance.

6

⚑ What is FastAPI, and why use it?

In simple words

FastAPI is a Python web framework for building APIs. A framework is a ready-made structure. It does the work that is the same in every project: reading HTTP, finding the right function for an address, checking the incoming data, turning results into JSON, sending error answers. You fill in the functions. FastAPI was first released in 2018 by SebastiΓ‘n RamΓ­rez. It is open source under the MIT licence.

FastAPI is not built from nothing. It stands on two libraries, and a third program runs it.

  • Starlette is the web toolkit: routing, requests, responses, middleware, WebSockets. The class FastAPI is a child class of Starlette. The output below proves it.
  • Pydantic is the data toolkit. It reads Python type hints and checks and converts values with them: the text "3" becomes the number 3, and "abc" is refused with a precise message. Category 4 is all about it.
  • Uvicorn is the server: the program that opens the port, reads HTTP and calls your app. It talks to the app through ASGI, the Asynchronous Server Gateway Interface. ASGI is a standard plug. Any ASGI server (Uvicorn, Hypercorn, Daphne) can run any ASGI app (FastAPI, Starlette, Django). The older plug is WSGI. There is a table under the step cards.

Why do teams pick it? The word "fast" has two meanings.

  • Fast to run. It is built for async code. While one request waits for the database, the same worker can serve other requests (Category 9).
  • Fast to write. You declare what you expect with type hints, and FastAPI does the parsing, converting and checking.
  • Fewer bugs. Wrong data is stopped before your function runs, with a clear error for the client.
  • Documentation for free. Interactive docs are generated from the same code (step 11).

Be honest about what it does not bring: no database layer, no admin panel, no HTML pages by default. You add a database library in Category 6.

🎬 In the animation: the left side is a stack. From the top: your code, FastAPI (teal, in focus), Starlette and Pydantic side by side, a dashed line labelled ASGI, Uvicorn, and the network at the bottom. A blue dot, the request, climbs the right edge of the stack from the network up to your code, and Uvicorn, Starlette and your code blink as it passes. A green dot, the answer, comes down again, and Pydantic and Uvicorn blink. Then the four reasons appear as cards. The third card quotes a real answer of our demo below.

Real-time scenario

Without a framework Asha would write, for every single route: read the id from the URL, check that it is a number, convert it, send an error if it is not, and describe all of that in a separate document that is out of date a week later. With FastAPI she writes student_id: int, and all four things happen.

Code

# versions.py: what did pip install?
import fastapi, starlette, pydantic, uvicorn
from fastapi import FastAPI

print(fastapi.__version__, starlette.__version__,
      pydantic.__version__, uvicorn.__version__)

# the parent class of FastAPI is Starlette
print(FastAPI.__mro__[1])

Output

0.143.0 1.7.0 2.14.0 0.54.0
<class 'starlette.applications.Starlette'>

Now the main reason in one small demo. It is a preview of Category 2, so do not worry about the details. Look only at the type hint student_id: int.

# why_demo.py: a preview of Category 2. One type hint does three jobs.
from fastapi import FastAPI

app = FastAPI()
students = {1: "Asha", 2: "Ravi", 3: "Meena", 4: "Kiran", 5: "Farhan", 6: "Divya"}


@app.get("/students/{student_id}")
def get_student(student_id: int):
    return {"id": student_id, "name": students[student_id], "type": type(student_id).__name__}
uvicorn why_demo:app
curl http://127.0.0.1:8000/students/3
curl -i http://127.0.0.1:8000/students/abc

Output

{"id":3,"name":"Meena","type":"int"}
HTTP/1.1 422 Unprocessable Content
...
{"detail":[{"type":"int_parsing","loc":["path","student_id"],"msg":"Input should be a valid integer, unable to parse string as an integer","input":"abc"}]}

That one hint did three jobs. It converted the text "3" from the URL into the number 3 ("type":"int"). It refused "abc" with a message that says where the problem is (path, student_id) and what is wrong, and our function was never called. And it wrote "type": "integer" for this parameter into the generated documentation.

Common mistake

Watch out: FastAPI is not a server. It is the application. Uvicorn is the server that runs it. This is why an interviewer who hears "FastAPI runs on port 8000" asks "what runs it?". The answer: an ASGI server, usually Uvicorn.

7

πŸ“¦ Installing FastAPI and Uvicorn

In simple words

Python packages come from PyPI, the public shop of Python packages, and pip is the program that fetches them. The question is where pip puts them. If every project installs into the one Python of the computer, two projects that need different versions break each other. The answer is a virtual environment: a folder, by habit named .venv, that holds a private copy of Python and its own packages for one project.

  • python -m venv .venv creates that folder. You do it once per project. On Linux and macOS the command is often python3.
  • source .venv/bin/activate switches the current terminal to it. On Windows it is .venv\Scripts\activate. The prompt now starts with (.venv). You do this in every new terminal.
  • pip install "fastapi[standard]" installs FastAPI together with its standard helpers. The square brackets ask for "extras": optional packages that the authors recommend.

What do the extras add? The most important one is Uvicorn, the server. Then the fastapi command (step 9), httpx for calling and testing APIs, and helpers for forms, e-mail addresses and settings. On the day we ran it, the one command installed 56 packages. Without the brackets, pip install fastapi installed only 11 and no server, and then fastapi dev main.py stopped with the message To use the fastapi command, please install "fastapi[standard]". Old tutorials write pip install fastapi uvicorn. That still works, but it gives you less.

🎬 In the animation: the laptop on the left holds the system Python at the top and the project folder rp_academy/ below it. With command 1 the teal box .venv/ appears inside the project folder. With command 2 the green pill "(.venv) active" switches on. With command 3 nine pills fly into the box: the four teal ones you must know (fastapi, starlette, pydantic, uvicorn), four helpers, and "+ 48 more", which makes 56. Command 4 asks the new fastapi command for its version.

Real-time scenario

Asha's laptop still has a college project that needs an old version of Pydantic. If she installed FastAPI for the whole laptop, pip would replace that Pydantic and the old project would stop working. With one .venv per project folder, each project keeps its own versions, and deleting a project folder removes everything that belonged to it.

Code

mkdir rp_academy
cd rp_academy
python -m venv .venv
source .venv/bin/activate
which python                      # Windows: where python
python --version
pip install "fastapi[standard]"
fastapi --version

Output (the long list that pip prints is shortened)

/home/asha/rp_academy/.venv/bin/python
Python 3.13.16
Collecting fastapi[standard]
...
Successfully installed MarkupSafe-3.0.4 agent-detector-2.0.0 annotated-doc-0.0.5 ...
FastAPI CLI version: 0.0.32
FastAPI Cloud CLI version: 0.26.0

The first line is the check that matters: python now means the Python inside .venv. To give a teammate exactly your versions, write them to a file and put that file in Git. The teammate creates a fresh environment and installs from the file.

pip freeze > requirements.txt          # you: one line per package, 56 lines here
pip install -r requirements.txt         # the teammate, in a new environment

Common mistake

Watch out: the environment is active only in the terminal where you activated it. Open a new terminal, forget to activate, and Python answers ModuleNotFoundError: No module named 'fastapi' although you installed it yesterday. Look for (.venv) in the prompt before you blame the code. A second trap: never name your own file fastapi.py. Python then imports your file instead of the library, and the error is ImportError: cannot import name 'FastAPI' from 'fastapi'.

8

✍️ Creating your first FastAPI application

In simple words

Create a file main.py in the project folder. The first application has seven lines and four ideas.

  • Import. from fastapi import FastAPI takes the class FastAPI from the package you installed. Mind the capital letters.
  • The app object. app = FastAPI() creates the application. Everything else is attached to this object, and the server will look for it by its name.
  • A decorator. A line that starts with @, placed directly above a function, hands that function to something else. @app.get("/") hands the function to the app with the instruction: "when a GET request for the path / arrives, call this". The app writes that into its route table. There is one decorator per HTTP method: @app.post, @app.put, @app.delete (Category 2).
  • The function. A normal Python function. FastAPI calls it a path operation function: "path" is the URL part and "operation" is the HTTP method. Its name does not appear in the URL. Whatever it returns, here a dict, FastAPI converts to JSON and sends with status 200.

The route table is filled once, when Python reads the file at startup. It is not rebuilt for every request. A function can return a dict, a list, a text, a number, and later a Pydantic model (Category 4).

🎬 In the animation: four cards appear on the left, one for each idea, numbered in the order of the code. When card 3 (the decorator) appears, a teal pill "GET / β†’ home()" flies from it into the route table on the right: the route is registered. Under it three grey lines appear: /docs, /redoc and /openapi.json, routes that FastAPI adds by itself. The middle card shows the dict that the function returns and the 39 bytes of JSON that FastAPI sends. In the last card a blue GET / visits the route table and a green 200 OK appears.

Real-time scenario

Asha's first goal is small on purpose: prove that the whole chain works, from a request to an answer. So the first route only returns a welcome message. Real teams start the same way: first a "hello" route, then /health so that monitoring tools can ask "are you alive?", and only then the routes with real data.

Code

from fastapi import FastAPI

app = FastAPI()


@app.get("/")
def home():
    return {"message": "Welcome to RP Academy API"}

With the server of the next step running, this is the complete answer to curl -i http://127.0.0.1:8000/:

HTTP/1.1 200 OK
date: Sun, 11 Oct 2026 17:37:21 GMT
server: uvicorn
content-length: 39
content-type: application/json

{"message":"Welcome to RP Academy API"}

You wrote none of the headers. FastAPI set the status and the content type, counted the 39 bytes, and Uvicorn added the date and its own name.

Common mistake

Watch out: python main.py prints nothing and returns to the prompt. We tried it. The file only describes the app. Nothing in it opens a port. A server has to import the file and keep running, and that is the next step.

9

▢️ Running the application locally, with reload

In simple words

"Locally" means on your own computer. There are three commands you must know. All of them start Uvicorn.

CommandWhat it doesUse it
fastapi dev main.pyFinds the app object in the file, starts Uvicorn on 127.0.0.1:8000 and restarts it whenever a file changes.Every day while you write code.
uvicorn main:app --reloadThe same job, spelled out. main is the file main.py without the ending, app is the variable in it, --reload turns the restart on.Older projects, blogs and interview questions use this form.
fastapi run main.pyProduction style: no reload, and it listens on 0.0.0.0, which means "every network card of this computer", so other computers can reach it.Inside a Docker container or on a server (Category 12).

Reload works with two processes. A small reloader process watches the folder. The server process answers the requests. When you save a file, the reloader stops the server process and starts a new one, which reads the new code. This is perfect for learning and wrong for production: it costs time, and every restart forgets everything that was only in memory. A student that you added to the Python list is gone after the next save. That is one reason why Category 6 brings a database.

Stop the server with Ctrl+C. Run every command inside the project folder with the environment active.

🎬 In the animation: the middle card is the terminal. Its lines appear in the real order: the command, "Server started", "Application startup complete". Then a blue GET /students flies from the browser on the right into the terminal. The log line ends in an orange 404 and the browser shows {"detail":"Not Found"}, because version 1 has no such route. In the editor on the left four teal lines appear and a "saved" pill flies to the terminal. The terminal answers "WatchFiles detected changes in 'main.py'. Reloading..." and starts again. The browser asks once more, and now the log ends in a green 200 and the browser lists the 6 students.

Real-time scenario

Asha keeps three windows open all day: the editor, the terminal with fastapi dev, and the browser. She changes a line, presses Ctrl+S, and one second later refreshes the browser. Without reload she would press Ctrl+C, arrow-up and Enter two hundred times a day, and she would lose time looking for a bug that was only an old server still running old code.

Code

Start version 1 from step 8, then replace the file with this complete main.py and save. It is the state of the project at the end of this page.

from fastapi import FastAPI

app = FastAPI(
    title="RP Academy API",
    description="Students and courses of RP Academy.",
    version="0.1.0",
)

# Category 1 keeps the data in memory. Category 6 moves it to a database.
students = [
    {"id": 1, "name": "Asha", "city": "Hyderabad", "course_id": 2},
    {"id": 2, "name": "Ravi", "city": "Chennai", "course_id": 1},
    {"id": 3, "name": "Meena", "city": "Pune", "course_id": 3},
    {"id": 4, "name": "Kiran", "city": "Warangal", "course_id": 2},
    {"id": 5, "name": "Farhan", "city": "Bengaluru", "course_id": 3},
    {"id": 6, "name": "Divya", "city": "Hyderabad", "course_id": 1},
]


@app.get("/")
def home():
    return {"message": "Welcome to RP Academy API"}


@app.get("/health")
def health():
    """Is the API alive? Monitoring tools call this."""
    return {"status": "ok"}


@app.get("/students")
def list_students():
    """All students of RP Academy."""
    return students
fastapi dev main.py

The terminal: start, a 404 for /students, the save, and the 200 after the reload

 ⚑️ Starting FastAPI in development mode

 🐍 Using import string: main:app

 🌐 Server started at http://127.0.0.1:8000
    Documentation at http://127.0.0.1:8000/docs

  Logs:

 β–•  Will watch for changes in these directories: ['/home/asha/rp_academy']
 β–•  Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
 β–•  Started reloader process [19] using WatchFiles
 β–•  Started server process [51]
 β–•  Waiting for application startup.
 β–•  Application startup complete.
 β–•  127.0.0.1:38110 - "GET / HTTP/1.1" 200
 β–•  127.0.0.1:38126 - "GET /students HTTP/1.1" 404
 β–•  WatchFiles detected changes in 'main.py'. Reloading...
...
 β–•  Finished server process [51]
 β–•  Started server process [78]
 β–•  Waiting for application startup.
 β–•  Application startup complete.
 β–•  127.0.0.1:38132 - "GET /students HTTP/1.1" 200
 β–•  127.0.0.1:38138 - "GET /health HTTP/1.1" 200

Read it once slowly. "Using import string: main:app" means the command found the object app in main.py. The server process was number 51 before the save and number 78 after it: a new process with the new code. With uvicorn main:app --reload the same lines appear with the prefix INFO:.

Test it yourself: open http://127.0.0.1:8000/students in a browser. You see one long line of JSON with 6 students. In a terminal, curl -s http://127.0.0.1:8000/students | python -m json.tool prints the same answer with one field per line, starting with "id": 1, and "name": "Asha",.

Common mistake

Watch out: three real error messages that every beginner meets. Starting a second server while the first still runs: [Errno 98] error while attempting to bind on address ('127.0.0.1', 8000): address already in use. Stop the old one, or add --port 8001. A wrong name after the colon, uvicorn main:App: Attribute "App" not found in module "main". Running the command from the wrong folder, or writing main.py:app: Could not import module "main". The part before the colon is a module name, not a file name with its ending.

10

πŸ”„ The request and response lifecycle

In simple words

"Lifecycle" means everything that happens between the moment a client sends a request and the moment it holds the answer. For GET /students there are eight stops.

  1. The client sends. It opens a connection to 127.0.0.1, port 8000, and writes the request text of step 3.
  2. Uvicorn receives and reads. It turns the raw bytes into Python values: the method GET, the path /students, the headers. It hands them to the app through ASGI.
  3. FastAPI finds the route. It looks in the route table for an entry with this method and this path, and finds list_students. If the function had parameters, FastAPI would now read and check them (Categories 2 to 4).
  4. Your function runs. It is plain Python. It has no idea that HTTP exists.
  5. Your function returns a Python list of 6 dicts.
  6. FastAPI builds the response. It converts the list to JSON text (334 bytes), sets the status 200 and the headers content-type and content-length.
  7. Uvicorn sends and logs. It writes the status line, the headers and the body to the connection, and one line to the terminal.
  8. The client shows the result. A browser prints the JSON. An app draws a list.

Three things can end the journey early, and each has its own status code. No matching route at stop 3: FastAPI answers 404 and your code never runs. Wrong data in the request at stop 3: FastAPI answers 422, as in step 6. An error inside your function at stop 4: the client gets 500, and the full traceback is printed in the terminal of the server, not sent to the client.

🎬 In the animation: four stations stand in a row: Client, Uvicorn, FastAPI (teal), your function. A blue GET /students pill moves along the blue line from station to station, passing the badges 1 to 4. At the function it turns into a purple "list of 6 dicts", goes around the corner, and becomes a green "200 · JSON" that travels back along the green line past the badges 5 to 8. Under each station two cards explain its two stops: the top row is the way in, the bottom row the way back, so the cards under FastAPI are 3 and 6. The strip at the bottom shows the three early endings.

Real-time scenario

A request "does not work". Asha uses the lifecycle as a checklist. Is there a log line in the terminal? If not, the request never reached Uvicorn: wrong port, or the server is down. Is the status 404? Then no route matched: check the path and the method. Does her print() appear? If not, the function was never called. Is there a traceback? Then the function crashed, and the last lines name the file and the line.

Code

To watch the stops yourself, put print() lines into a function. This small file also has a route with a bug.

# trace_main.py: two print() lines and one bug, to watch the lifecycle in the terminal
from fastapi import FastAPI

app = FastAPI()
students = [{"id": 1, "name": "Asha"}, {"id": 2, "name": "Ravi"}]


@app.get("/students")
def list_students():
    print("stop 4: list_students() is running")
    print("stop 5: it returns a", type(students).__name__, "of", len(students), "items")
    return students


@app.get("/broken")
def broken():
    return 10 / 0        # a bug in our own code
uvicorn trace_main:app
curl -i http://127.0.0.1:8000/students
curl -i http://127.0.0.1:8000/teachers
curl -i http://127.0.0.1:8000/broken

The terminal of the server (the long traceback is shortened to its last lines)

stop 4: list_students() is running
stop 5: it returns a list of 2 items
INFO:     127.0.0.1:40122 - "GET /students HTTP/1.1" 200 OK
INFO:     127.0.0.1:40130 - "GET /teachers HTTP/1.1" 404 Not Found
INFO:     127.0.0.1:40132 - "GET /broken HTTP/1.1" 500 Internal Server Error
ERROR:    Exception in ASGI application
Traceback (most recent call last):
...
  File "/home/asha/rp_academy/trace_main.py", line 17, in broken
    return 10 / 0        # a bug in our own code
           ~~~^~~
ZeroDivisionError: division by zero

What the client got for /broken

HTTP/1.1 500 Internal Server Error
date: Sun, 11 Oct 2026 17:45:46 GMT
server: uvicorn
content-length: 21
content-type: text/plain; charset=utf-8

Internal Server Error

Three things to see. The two print lines appear before the log line of the same request: the function runs first, the log is written when the answer goes out. For /teachers no print line appears: the function never ran. And for /broken the client learns only "Internal Server Error". The details stay on the server, which is good, because a traceback tells an attacker a lot about your code.

Common mistake

Watch out: print() writes to the terminal of the server. The client receives only what the function returns. A function that prints the students and returns nothing sends the answer null. And remember the other half: code at the top of main.py, such as the students list, runs once at startup. Only the function body runs for every request.

11

πŸ“š Automatic documentation: Swagger UI, ReDoc and the OpenAPI specification

In simple words

Somebody has to tell the app developer which addresses exist, what to send and what comes back. Writing that by hand is slow, and it is wrong the day after the code changes. FastAPI solves this with three addresses that every app gets without one extra line.

AddressWhat it isWho uses it
/openapi.jsonThe OpenAPI specification of your API: one JSON document that lists every path, method, parameter and response. OpenAPI is a public standard for describing HTTP APIs, not a FastAPI invention. FastAPI writes version 3.1.0 of it.Programs: Swagger UI and ReDoc themselves, Postman, API gateways, code generators that write a client library for you.
/docsSwagger UI: a web page that draws that JSON as a list of routes. Every route has a "Try it out" button that sends a real request from the browser and shows the status, the body and the headers.You, while you build. Testers. The developer of the app.
/redocReDoc: another page that draws the same JSON, laid out for reading: a menu on the left, descriptions in the middle, examples on the right.People who want to read about your API, for example a partner company.

Where does the content come from? From your code, and from nowhere else. title, description and version come from FastAPI(...). Each decorator gives one path and method. The function name becomes the summary: list_students is shown as "List Students". The docstring, the text in triple quotes under the def line, becomes the description. Type hints become the data types (Categories 2 to 4).

A word about names. The standard was called the Swagger specification until it was renamed OpenAPI in 2016. "Swagger" lives on as the name of tools such as Swagger UI. So when somebody says "send me the Swagger", they mean the OpenAPI document or the /docs page.

🎬 In the animation: on the left is main.py with its 3 routes as blue pills. They fly into the middle card, /openapi.json, and arrive as 3 purple pills: the 3 entries under "paths", written by FastAPI. Two arrows lead to two browser windows. In the Swagger UI window three blue GET rows appear, then "Try it out", "Execute" and a green 200. In the ReDoc window the menu, the description from the docstring and a dark box with response samples appear. 3 routes in the code, 3 paths in the JSON, 3 rows in each page. The code panel shows a real, shortened piece of the JSON.

Real-time scenario

The developer of the mobile app asks: "what exactly does /students return?" Asha does not write a document. She sends the link to /docs. Kiran, who tests the API, tries every route with "Try it out" and installs nothing. Next week Asha adds a POST route, and the page shows it the moment she saves.

Code

curl -s http://127.0.0.1:8000/openapi.json | python -m json.tool --indent 2

Output (the entries for / and /health look like the one for /students and are left out)

{
  "openapi": "3.1.0",
  "info": {
    "title": "RP Academy API",
    "description": "Students and courses of RP Academy.",
    "version": "0.1.0"
  },
  "paths": {
...
    "/students": {
      "get": {
        "summary": "List Students",
        "description": "All students of RP Academy.",
        "operationId": "list_students_students_get",
        "responses": {
          "200": {
            "description": "Successful Response",
            "content": {
              "application/json": {
                "schema": {}
              }
            }
          }
        }
      }
    }
  }
}

Test it yourself: open http://127.0.0.1:8000/docs. Click the row "GET /students", then "Try it out", then "Execute". Under "Responses" you see the code 200 and the 6 students, and above them the exact curl command that Swagger UI used. Then open /redoc and /openapi.json. The browser tab of /docs is titled "RP Academy API - Swagger UI": your title.

Common mistake

Watch out: the docs show what the code says, not what you meant. Look at "schema": {} in the output: it is empty. Our function has no type hints for its result, so the documentation cannot tell the app developer which fields a student has. Category 3 fills it in with response_model. Also know that the /docs page loads Swagger UI from the internet (a CDN), so it stays blank on a computer without internet although the API itself works.

12

βš–οΈ FastAPI vs Flask vs Django

In simple words

All three are Python web frameworks, all three are free, and all three run real products. They differ in how much they bring and what they were made for.

  • Flask (2010) is a micro framework. The core gives you routing, HTML templates and a development server, and stays out of your way. Validation, API documentation, a database layer and login are extensions that you choose and connect yourself. It is easy to start with, and a huge amount of existing code uses it.
  • Django (2005) is a full-stack framework, "batteries included". It brings its own database layer (the ORM) with migrations, an admin panel, user accounts and login, forms and HTML templates, all designed to fit together. For JSON APIs teams add Django REST Framework or Django Ninja.
  • FastAPI (2018) is an API framework. It brings what an API needs: validation from type hints, JSON in and out, generated documentation, dependency injection (Category 5), and async from the start. It has no ORM, no admin panel and no page templates of its own.

How to choose in practice. You need a complete website with an admin screen and login quickly: Django. You need an API for a mobile app, a microservice, a service around a machine learning model or a data pipeline: FastAPI. You need a small site or tool and want to pick every part yourself, or the company already has Flask code: Flask. Speed tests on the internet often put FastAPI with Uvicorn ahead, but in real projects the database is usually the slow part, so choose by features and by what your team knows.

🎬 In the animation: three lanes appear from left to right: Flask, Django, FastAPI (teal). Each has the same four rows: what it is, what is in the box, what you add yourself, what to pick it for. Then the last block, "We ran it", fills in all three lanes: the status code each framework really returned for /students, /students/abc and /docs. Green pills are 2xx, orange pills are 4xx.

Real-time scenario

RP Academy needs data for a mobile app, so Asha's batch builds a FastAPI service. If the owner had asked for a public website with course pages, a blog and an office screen to edit students, ready in two weeks, Django would win because its admin panel is free. For a one-page fee calculator for the front desk, Flask is plenty. Many companies run Django for the website and FastAPI for the APIs next to it.

Code

The same two routes in all three. We really ran them, in one environment with Flask 3.1.3, Django 6.1.2 and FastAPI 0.143.0. All three import the same 6 students from a small file data.py.

# flask_app.py
from flask import Flask

from data import students          # the same 6 rows as main.py

app = Flask(__name__)


@app.get("/students")
def list_students():
    return students


@app.get("/students/<int:student_id>")
def get_student(student_id):
    return students[student_id - 1]
# rp_site/views.py
from django.http import JsonResponse

from data import students          # the same 6 rows as main.py


def list_students(request):
    return JsonResponse(students, safe=False)


def get_student(request, student_id):
    return JsonResponse(students[student_id - 1])
# rp_site/urls.py
from django.contrib import admin
from django.urls import path

from . import views

urlpatterns = [
    path("admin/", admin.site.urls),
    path("students", views.list_students),
    path("students/<int:student_id>", views.get_student),
]
# fastapi_app.py
from fastapi import FastAPI

from data import students          # the same 6 rows as main.py

app = FastAPI()


@app.get("/students")
def list_students():
    return students


@app.get("/students/{student_id}")
def get_student(student_id: int):
    return students[student_id - 1]

What each one answered: status, content type and the start of the body

GET /students
  Flask   200  application/json          [{"city":"Hyderabad","course_id":2,"id":1,"n ...   (6 students)
  Django  200  application/json          [{"id": 1, "name": "Asha", "city": "Hyderaba ...   (6 students)
  FastAPI 200  application/json          [{"id":1,"name":"Asha","city":"Hyderabad","c ...   (6 students)
GET /students/abc
  Flask   404  text/html; charset=utf-8  <!doctype html> <html lang=en> <title>404 No ...
  Django  404  text/html; charset=utf-8  <!DOCTYPE html> <html lang="en"> <head> <met ...
  FastAPI 422  application/json          {"detail":[{"type":"int_parsing","loc":["pat ...
GET /docs
  Flask   404  text/html; charset=utf-8  <!doctype html> <html lang=en> <title>404 No ...
  Django  404  text/html; charset=utf-8  <!DOCTYPE html> <html lang="en"> <head> <met ...
  FastAPI 200  text/html; charset=utf-8  <!DOCTYPE html> <html> <head> <meta name="vi ...

Read it fairly. All three return the 6 students in a few lines of code. The Django part looks short too, but it sits inside a project that django-admin startproject generated, with a settings file of 127 lines: that is the price and the value of "batteries included". Flask sorted the keys of each student by alphabet. For a wrong id, Flask and Django say "no such page" with an HTML page made for people, while FastAPI answers a program in JSON and says what is wrong. And only FastAPI has documentation at /docs without an add-on.

Common mistake

Watch out: do not answer "which is best?" with one name. Wrong in an interview: "FastAPI is the best because it is the fastest." Right: say what each brings out of the box, name one case where you would pick each, and then say why this project needs this one.

Comparison tables and cheat sheets

FastAPI vs Flask vs Django

🌢️ Flask🎸 Django⚑ FastAPI
First release201020052018
KindMicro frameworkFull-stack frameworkAPI framework
Server interfaceWSGIWSGI and ASGIASGI
AsyncAsync views are possible, but each request still holds one workerAsync views and ASGI are supported, and the ORM has async methodsBuilt for it: async def routes, and plain def routes run in a thread pool
Checking the inputAn extension, or by handForms, or serializers of Django REST FrameworkBuilt in, from type hints (Pydantic)
API documentationAn extensionAn extensionBuilt in: /docs, /redoc, /openapi.json
Database layerAn extension, usually SQLAlchemyBuilt in: the Django ORM with migrationsNot included. You choose, usually SQLAlchemy (Category 6)
Admin panel, loginExtensionsBuilt inNot included. Login is built in Category 7
HTML pagesYes, Jinja2 templatesYes, Django templatesPossible with Jinja2, but not the focus
Pick it forSmall sites and services, existing Flask codeComplete websites with admin and loginAPIs, microservices, data and ML services

HTTP vs HTTPS

HTTPHTTPS
On the wirePlain text that anybody on the way can readThe same message, encrypted by TLS
Port when the address names none80443
CertificateNoneThe server needs one, signed by a certificate authority
Proves who the server isNoYes
A change on the wayGoes unnoticedIs detected, and the message is dropped
Where it is fineYour own laptop, or inside a private network behind a proxyEverything that crosses the internet

ASGI vs WSGI

WSGIASGI
Full nameWeb Server Gateway InterfaceAsynchronous Server Gateway Interface
What it isA standard for how a Python web server hands a request to a Python application. Because of it, any server can run any framework that speaks the same standard.
How a request is handledOne blocking function call. The worker is busy until the answer is readyAn async call. While one request waits for a database, the same worker serves others
WebSockets, long connectionsNoYes
ServersGunicorn, uWSGI, WaitressUvicorn, Hypercorn, Daphne
FrameworksFlask, classic DjangoFastAPI, Starlette, Django as well

Why this matters in data engineering work: an API that calls a database, S3 or another API spends most of its time waiting. With ASGI one worker can wait on many of those calls at once.

Three addresses for "this computer"

AddressMeaning
127.0.0.1This computer, and only this computer. fastapi dev and uvicorn listen here by default, so nobody else on the Wi-Fi can reach your half-finished API.
localhostThe name of 127.0.0.1. http://localhost:8000 opens the same server.
0.0.0.0As a listening address it means "every network card of this computer". Other computers can then reach the server through the IP address of the machine. fastapi run listens here.

Commands of this page

CommandWhat it does
python -m venv .venvCreate the virtual environment, once per project
source .venv/bin/activateActivate it, in every new terminal. Windows: .venv\Scripts\activate. Leave it with deactivate
pip install "fastapi[standard]"Install FastAPI, Uvicorn and the helpers
fastapi dev main.pyRun with reload on 127.0.0.1:8000. Add --port 8001 for another port
uvicorn main:app --reloadThe same, asked of Uvicorn directly
fastapi run main.pyProduction style: no reload, listens on 0.0.0.0
curl -i URLShow the status line, the headers and the body. -v also shows the request, -X POST sets the method
Ctrl+CStop the server

Old names you will still meet

In old blogs and company codeToday
pip install fastapi uvicornpip install "fastapi[standard]"
uvicorn main:app --reload as the only way to startfastapi dev main.py. The uvicorn command still works and is good to know
"Swagger specification", "send me the Swagger"OpenAPI specification. Swagger UI is the page that draws it
SSLTLS. The old word survives in names such as --ssl-keyfile
422 Unprocessable Entity422 Unprocessable Content: the same code with its newer official phrase, which is what our server printed

Worth knowing (not in the animation)

Mistakes beginners make

  1. Running python main.py and waiting. Nothing happens, because the file only describes the app. Start a server: fastapi dev main.py.
  2. Forgetting to activate the environment. "No module named 'fastapi'" or "fastapi: command not found" in a new terminal almost always means the prompt does not show (.venv).
  3. Installing only fastapi. Without [standard] there is no server and no fastapi command. Install "fastapi[standard]", with the quotes.
  4. A wrong start string. uvicorn main:app means file main.py, variable app, run from the folder that holds the file. If your file is server.py and the object is api, the string is server:api.
  5. An old server that still holds the port. "Address already in use" means a server from an earlier terminal is still running. Find that terminal and press Ctrl+C. Worse is the silent version: you test in the browser against the old server and wonder why your change does nothing.
  6. Trusting data in memory. The Python list is rebuilt from the code at every reload and every restart. It is fine for learning the routes. Real data needs a database.
  7. Using reload in production. fastapi dev and --reload watch files, restart often and are made for one developer. Production uses fastapi run or plain uvicorn without reload (Category 12).
  8. Putting .venv in Git, or leaving out requirements.txt. The environment is large and belongs to one computer. Commit the list of packages, not the packages.

Try it yourself

  1. A second resource. Add the 3 courses (id, title, fee, level) from the top of this page as a Python list, and a route GET /courses that returns them. Hint: a correct result is a list of 3 objects, and the first has the title "Python Basics" and the fee 4000. The terminal shows a reload when you save, and /docs now has 4 GET rows. The new row is called "List Courses" if your function is named list_courses.
  2. Read the conversation. With the server running, call /students/ (with a slash at the end) and /Students (capital S) with curl -i. Hint: the first answers 307 and has a location header, the second answers 404. Write one sentence for each that says why. Then add -L to the first command and watch curl follow the redirect to a 200.
  3. Your own client. Write city_report.py. It must call /students with httpx and print how many students live in each city. Do not change main.py. Hint: a correct result names 5 cities. Hyderabad has 2 and the other four have 1 each, which makes 6.
  4. Break it on purpose. Produce three errors and write down the last line of each and its cure: run report.py with the server stopped, start a second server while the first is running, and start with uvicorn main:App. Hint: you should meet "Connection refused", "address already in use" and "Attribute "App" not found". If you can explain all three, you will not lose an afternoon to them later.
  5. Change the documentation without touching it. In main.py change the version to "0.2.0" and give home() a docstring of one sentence. Hint: after the save, /openapi.json shows "version": "0.2.0" and a new "description" inside the entry for "/". Refresh /docs: the header shows 0.2.0 and the row "GET /" shows your sentence when you open it.

Interview questions

Q. What is FastAPI, and why would you choose it?

FastAPI is a Python framework for building APIs. I write normal functions with type hints, and from those hints it validates the input, converts the data, returns JSON and generates interactive documentation. It is built on Starlette and Pydantic and runs on an ASGI server, so it supports async code well. I choose it when the product is an API: a backend for an app, a microservice, or a service around a model or a data pipeline.

Q. FastAPI vs Flask vs Django: how do you decide?

I look at what each brings out of the box. Django is full-stack: ORM, migrations, admin panel and login, so it is my choice for a complete website with an admin screen. Flask is a small core where I pick every extension myself, good for small services and where a team already has Flask code. FastAPI is made for APIs: validation, documentation and async are built in, but it has no ORM and no admin. For a JSON API that a mobile app or other services call, I pick FastAPI.

Q. What is the difference between FastAPI and Uvicorn?

FastAPI is the application: my routes and the rules around them. Uvicorn is the server: the program that opens the port, reads HTTP and calls the application for each request. They talk through ASGI, a standard interface, so I could run the same app with another ASGI server such as Hypercorn. The command uvicorn main:app says exactly this: Uvicorn, run the object app from the module main.

Q. What is ASGI, and how is it different from WSGI?

Both are standards for how a Python web server passes a request to a Python application. WSGI is the older one: one blocking call per request, so a worker is busy until the response is ready, and there are no WebSockets. ASGI is asynchronous: while one request waits for a database or another API, the same worker can handle other requests, and long-lived connections are possible. Flask is WSGI, FastAPI is ASGI, and Django supports both.

Q. What do Starlette and Pydantic do inside FastAPI?

Starlette is the web layer: routing, request and response objects, middleware and WebSockets. The FastAPI class is a subclass of the Starlette class. Pydantic is the data layer: it validates and converts values using type hints and produces the schemas for the documentation. FastAPI connects the two, so that one type hint gives validation, conversion and documentation together.

Q. What happens when a request reaches a FastAPI application?

Uvicorn accepts the connection and parses the HTTP text into method, path, headers and body. It passes them to the app through ASGI. FastAPI matches the method and the path against its routes. If nothing matches, it returns 404. It then reads and validates the parameters and returns 422 if they are wrong. Then it calls my function, converts the return value to JSON, sets the status code and the headers, and Uvicorn sends the response and writes an access log line. If my function raises an error, the client gets 500 and the traceback is in the server log.

Q. What is a REST API, and what does stateless mean?

REST is a style for HTTP APIs. Resources have addresses made of nouns, such as /students/3, the HTTP method is the verb, the data travels as JSON, and status codes report the result. Stateless means the server keeps no memory of earlier requests of a client: every request carries all it needs, for example a token. Because of that, any copy of the server can answer any request, which makes it easy to run many copies behind a load balancer.

Q. What is the difference between HTTP and HTTPS?

The message is the same. HTTPS sends it through TLS. That gives three things: encryption, so nobody on the network can read it; a certificate, so the client knows it is talking to the real server; and integrity, so nobody can change it on the way. HTTP uses port 80 and HTTPS port 443 by default. In production I usually end TLS at a load balancer or proxy in front of Uvicorn.

Q. How does FastAPI generate its documentation? What are OpenAPI, Swagger UI and ReDoc?

At startup FastAPI knows every route, its parameters and its types, because I declared them in code. From that it builds an OpenAPI document and serves it at /openapi.json. OpenAPI is a standard format for describing HTTP APIs. Swagger UI at /docs and ReDoc at /redoc are two web pages that read this document: Swagger UI is interactive and lets me send requests, ReDoc is laid out for reading. Because all of it comes from the code, it cannot fall behind the code.

Q. What does uvicorn main:app --reload mean, and would you use it in production?

main is the Python module, the file main.py. app is the FastAPI object inside it. --reload starts a watcher that restarts the server whenever a source file changes. The newer command fastapi dev main.py does the same. I use reload only in development. In production I start without it, with fastapi run or plain Uvicorn, usually with several workers, because reloading costs resources and a restart drops whatever was in memory.

All code on this page was run in October 2026 with FastAPI 0.143, Pydantic 2.14 and Python 3.13. Official documentation: FastAPI, First Steps, FastAPI CLI, FastAPI features, Uvicorn settings, Starlette, Pydantic, OpenAPI Specification 3.1.0.