Day 16: Working with APIs using FastAPI
Introduction to APIs
An API (Application Programming Interface) acts as a bridge that allows two software systems to communicate with each other.
Basic Flow:
- Client (You/App) → Sends a request
- Server → Processes the request
- Server → Sends a response
Real-Life Example: Weather App
- App sends a request to a weather API
- API processes it
- API returns weather data (temperature, humidity, etc.)
Types of APIs
1. REST API
- Most commonly used
- Uses HTTP methods
- Example: Food delivery apps (Swiggy, Zomato)
2. SOAP API
- More secure, structured
- Used in banking systems
- Example: Bank transactions
3. GraphQL API
- Fetch only required data
- Flexible and efficient
- Example: Modern web apps
HTTP Methods (Core of APIs)
| Method | Purpose |
|---|---|
| GET | Fetch data |
| POST | Send data |
| PUT | Update data |
| DELETE | Delete data |
What is FastAPI?
FastAPI is a modern Python web framework used to build APIs quickly and efficiently.
Key Features:
- High performance (uses async)
- Automatic API documentation (Swagger UI)
- Easy to learn
- Built-in validation using Pydantic
What is JSON?
JSON (JavaScript Object Notation) is the standard format used to exchange data between client and server.
Example:
{
"name": "Piyush",
"age": 21
}
What is Pydantic?
Pydantic ensures:
- Data validation
- Correct structure
- Type safety
Basic FastAPI Example
from fastapi import FastAPI
from pydantic import BaseModel
app = FastAPI()
@app.get("/")
def home():
return {"message": "Welcome to FastAPI!"}
@app.get("/users")
def get_users():
return ["Piyush", "Aman", "Amit"]
@app.get("/user/{user_id}")
def get_user(user_id: int):
return {"user_id": user_id}
@app.post("/create-user")
def create_user(user: dict):
return {
"message": "User created successfully",
"user": user
}
Using Pydantic Model
class User(BaseModel):
name: str
age: int
@app.post("/user-create")
def create_user1(user: User):
return {
"name": user.name,
"age": user.age
}
CRUD API Example (Students)
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
app = FastAPI()
class Student(BaseModel):
name: str
age: int
students = {}
@app.get("/students")
def get_students():
return students
@app.get("/students/{student_id}")
def get_student(student_id: int):
if student_id not in students:
raise HTTPException(status_code=404, detail="Student not found")
return students[student_id]
@app.post("/students/{student_id}")
def create_student(student_id: int, student: Student):
if student_id in students:
raise HTTPException(status_code=400, detail="Student already exists")
students[student_id] = student
return {"message": "Student created", "data": student}
@app.put("/students/{student_id}")
def update_student(student_id: int, student: Student):
if student_id not in students:
raise HTTPException(status_code=404, detail="Student not found")
students[student_id] = student
return {"message": "Student updated", "data": student}
@app.delete("/students/{student_id}")
def delete_student(student_id: int):
if student_id not in students:
raise HTTPException(status_code=404, detail="Student not found")
del students[student_id]
return {"message": "Student deleted"}
Summary
- APIs enable communication between systems
- HTTP methods define operations
- FastAPI simplifies API development
- JSON is used for data exchange
- Pydantic ensures data validation
- CRUD operations are essential for real-world APIs
Assignment Questions
Theory-Based
- What is an API? Explain with a real-world example.
- Differentiate between REST, SOAP, and GraphQL APIs.
- What are HTTP methods? Explain each with use cases.
- Why is JSON used in APIs?
- What is the role of Pydantic in FastAPI?
Practical Questions
-
Create a FastAPI app with:
- A GET route /hello returning "Hello World"
-
Create an API to:
- Add a product (name, price)
- Get all products
-
Build a CRUD API for:
- Books (title, author, price)
-
Modify the student API:
- Add email field
- Validate age should be greater than 5
-
Create an API endpoint:
- /square/{num} → returns square of a number
Challenge Task
Build a Mini User Management API:
- Add user
- Get all users
- Update user
- Delete user
- Use Pydantic validation
- Handle errors properly
.png)

0 Comments:
Post a Comment