Monday, 27 April 2026

April Python Bootcamp Day 16

 



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)

MethodPurpose
GETFetch data
POSTSend data
PUTUpdate data
DELETEDelete 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

  1. What is an API? Explain with a real-world example.
  2. Differentiate between REST, SOAP, and GraphQL APIs.
  3. What are HTTP methods? Explain each with use cases.
  4. Why is JSON used in APIs?
  5. What is the role of Pydantic in FastAPI?

Practical Questions

  1. Create a FastAPI app with:
    • A GET route /hello returning "Hello World"
  2. Create an API to:
    • Add a product (name, price)
    • Get all products
  3. Build a CRUD API for:
    • Books (title, author, price)
  4. Modify the student API:
    • Add email field
    • Validate age should be greater than 5
  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

0 Comments:

Post a Comment

Popular Posts

Categories

100 Python Programs for Beginner (119) AI (252) Android (25) AngularJS (1) Api (7) Assembly Language (2) aws (29) Azure (10) BI (10) Books (262) Bootcamp (11) C (78) C# (12) C++ (83) Course (87) Coursera (300) Cybersecurity (30) data (5) Data Analysis (32) Data Analytics (22) data management (15) Data Science (351) Data Strucures (17) Deep Learning (158) Django (16) Downloads (3) edx (21) Engineering (15) Euron (30) Events (7) Excel (19) Finance (10) flask (4) flutter (1) FPL (17) Generative AI (72) Git (10) Google (51) Hadoop (3) HTML Quiz (1) HTML&CSS (48) IBM (42) IoT (3) IS (25) Java (99) Leet Code (4) Machine Learning (291) Meta (24) MICHIGAN (5) microsoft (11) Nvidia (8) Pandas (14) PHP (20) Projects (32) pytho (1) Python (1325) Python Coding Challenge (1130) Python Mistakes (51) Python Quiz (489) Python Tips (5) Questions (3) R (72) React (7) Scripting (3) security (4) Selenium Webdriver (4) Software (19) SQL (49) Udemy (18) UX Research (1) web application (11) Web development (8) web scraping (3)

Followers

Python Coding for Kids ( Free Demo for Everyone)