FastAPI Basics
FastAPI is a modern Python framework used to build APIs and backend web services.
What is FastAPI?
FastAPI is a Python web framework mainly used for building APIs and backend applications.
It provides a simple way to define API endpoints, receive data from clients, process the data, and return responses.
Simple Definition
FastAPI is a Python framework used to build modern APIs and backend services.
Features of FastAPI
Simple API Development
API endpoints can be created using simple Python functions.
Type Hints
Python type hints can be used to describe the expected data.
Automatic Documentation
FastAPI can provide interactive API documentation for available endpoints.
JSON Responses
APIs can easily return structured data such as JSON responses.
FastAPI Request Flow
A client sends an HTTP request to a FastAPI endpoint. FastAPI processes the request and sends a response.
Client
Browser or application sends a request.
FastAPI
FastAPI receives and processes the request.
JSON Response
The API returns structured data to the client.
Installing FastAPI
FastAPI can be installed using pip.
pip install fastapi
To run the FastAPI application using the Uvicorn server, install Uvicorn as well.
pip install uvicorn
Creating Your First FastAPI Application
Create a Python file named main.py.
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
def home():
return {"message": "Hello from FastAPI"}
Understanding the Code
FastAPI Import
from fastapi import FastAPI
Imports the FastAPI class.
Application Object
app = FastAPI()
Creates the FastAPI application object.
GET Endpoint
@app.get("/")
Creates a GET endpoint for the root URL.
JSON Response
return {"message": "Hello from FastAPI"}
Returns data as a JSON-compatible response.
Running the FastAPI Application
Use Uvicorn to run the FastAPI application.
uvicorn main:app --reload
After starting the server, open the local URL in a browser.
http://127.0.0.1:8000/
Creating a GET Endpoint
A GET endpoint is commonly used to retrieve data.
from fastapi import FastAPI
app = FastAPI()
@app.get("/students")
def get_students():
return {
"students": [
"Rahul",
"Priya",
"Amit"
]
}
Creating Multiple Endpoints
A FastAPI application can contain many endpoints.
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
def home():
return {"message": "Home Page"}
@app.get("/about")
def about():
return {"message": "About Page"}
@app.get("/courses")
def courses():
return {
"courses": [
"Python",
".NET",
"Java"
]
}
Common HTTP Methods
| Method | Purpose | Example |
|---|---|---|
| GET | Retrieve data | /students |
| POST | Create new data | /students |
| PUT | Update existing data | /students/1 |
| DELETE | Delete data | /students/1 |
Path Parameters
A path parameter allows a value to be included directly in the URL.
from fastapi import FastAPI
app = FastAPI()
@app.get("/students/{student_id}")
def get_student(student_id: int):
return {
"student_id": student_id
}
For example, a request to /students/10 passes the value 10 to the function.
Query Parameters
Query parameters are values sent after the question mark in a URL.
from fastapi import FastAPI
app = FastAPI()
@app.get("/search")
def search(name: str):
return {
"search_name": name
}
Example URL:
http://127.0.0.1:8000/search?name=Python
Basic POST Endpoint
POST is commonly used when the client needs to send data to the server.
from fastapi import FastAPI
app = FastAPI()
@app.post("/students")
def create_student(name: str):
return {
"message": "Student created",
"name": name
}
Automatic API Documentation
FastAPI provides interactive API documentation that can be used to view and test API endpoints.
Swagger Documentation
Open the following URL after starting the application:
http://127.0.0.1:8000/docs
The page displays available endpoints and allows developers to test them.
Example: Course API 🤓📩
The following example creates a small API for displaying course information.
from fastapi import FastAPI
app = FastAPI()
@app.get("/courses")
def get_courses():
return {
"courses": [
{
"id": 1,
"name": "Python"
},
{
"id": 2,
"name": ".NET Full Stack"
},
{
"id": 3,
"name": "Java"
}
]
}
Flask vs FastAPI
| Feature | Flask | FastAPI |
|---|---|---|
| Main Use | Web applications and APIs | APIs and backend services |
| Learning | Simple | Simple with type hints |
| API Documentation | Additional setup may be required | Automatic documentation support |
| Type Hints | Optional | Commonly used |
Best Practices
- Use a virtual environment for each project.
- Use meaningful endpoint names.
- Use type hints for better readability.
- Validate incoming data.
- Keep business logic separate from route definitions as the project grows.
- Do not store passwords or secret keys directly in the source code.
Common Mistakes
- Forgetting to install FastAPI.
- Forgetting to install Uvicorn.
- Using the wrong application name in the Uvicorn command.
- Using incorrect endpoint URLs.
- Forgetting required type information for parameters.
- Sending data in an incorrect format.
Practice Exercise
Create a FastAPI application with these endpoints:
- / → Return a welcome message.
- /students → Return a list of students.
- /courses → Return a list of courses.
- /students/{id} → Return the requested student ID.
Start the application using Uvicorn and test the endpoints using the browser or API documentation.
Summary
FastAPI is a Python framework used to build APIs and backend services.
A FastAPI application is created using the FastAPI() class,
and endpoints can be defined using HTTP methods such as GET and POST.
Path parameters and query parameters can be used to receive data,
while FastAPI can return JSON responses to clients. Uvicorn can be
used to run the application, and FastAPI provides interactive API
documentation for testing and understanding endpoints.