0% found this document useful (0 votes)
18 views9 pages

Day 6 - Notes - Python Day 2 - FastAPI

This document provides an introduction to FastAPI, focusing on building high-performance RESTful APIs using Python. It covers web API fundamentals, setting up FastAPI, handling data and parameters, data validation with Pydantic, and asynchronous programming. Additionally, it includes lab exercises and a capstone project that involves creating an automated task management system with a FastAPI server and a client-side automation script.

Uploaded by

shubhali
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views9 pages

Day 6 - Notes - Python Day 2 - FastAPI

This document provides an introduction to FastAPI, focusing on building high-performance RESTful APIs using Python. It covers web API fundamentals, setting up FastAPI, handling data and parameters, data validation with Pydantic, and asynchronous programming. Additionally, it includes lab exercises and a capstone project that involves creating an automated task management system with a FastAPI server and a client-side automation script.

Uploaded by

shubhali
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Python - Python basics, Python Automation, introduction to FASTAPI

Day 2 – Introduction to FASTAPI (Module 3)

Module 3: Introduction to FastAPI

Objective: Build modern, high-performance RESTful APIs using Python's fastest-


growing web framework.

3.1 Web API Fundamentals

Objective: Understand the architecture of the web.

 REST API: A way for two computers to communicate over HTTP using
Resources (data) and Endpoints (URLs).
 HTTP Verbs:
o GET: Retrieve data (e.g., list tasks).
o POST: Create data (e.g., add a new task).
o PUT: Update data.
o DELETE: Remove data.

3.2 Getting Started with FastAPI

Objective: Set up your first server.

 Installation: Requires fastapi and uvicorn (the server that runs the code).
 Automatic Docs: FastAPI automatically generates interactive
documentation at /docs (Swagger UI). This allows you to test your API
without writing any frontend code.

Code Example: Hello World

Python
from fastapi import FastAPI

app = FastAPI()

@[Link]("/")
def read_root():
return {"message": "Hello KPMG!"}
3.3 Handling Data & Parameters

Objective: Make your API dynamic.

 Path Parameters: Used to identify a specific resource (e.g.,


/tasks/{task_id}).
 Query Parameters: Used for filtering or sorting (e.g.,
/tasks?status=completed).

Code Example: Parameters

Python
@[Link]("/items/{item_id}")
def read_item(item_id: int, q: str = None):
return {"item_id": item_id, "query": q}

3.4 Data Validation with Pydantic

Objective: Ensure incoming data is correct before processing it.

 Pydantic Models: Define the "shape" of your data using Python classes.
 Validation: If a user sends a string where an integer is expected, FastAPI
returns a clear error message automatically.

Code Example: Pydantic Schema

Python
from pydantic import BaseModel

class Task(BaseModel):
title: str
description: str | None = None
completed: bool = False
3.5 Asynchronous Programming

Objective: Understand why FastAPI is high-performance.

 Async/Await: Allows the server to handle other requests while waiting for a
slow task (like a database query) to finish.
 Performance: FastAPI is significantly faster than Flask because it is built
on ASGI (Asynchronous Server Gateway Interface).

Lab Exercises

Lab 1: The "Status Checker" API

1. Create a FastAPI app with a GET endpoint at /status.


2. It should return a JSON response: {"status": "online", "version": "1.0"}.
3. Run the app using uvicorn main:app --reload and verify it in the browser.

Lab 2: Dynamic User Greeting

1. Create an endpoint /hello/{name}.


2. Accept a query parameter called professional (a boolean).
3. If professional is true, return "Hello Mr./Ms. [name]". Otherwise, return
"Hey [name]!".

Lab 3: Task Creator (Pydantic)

1. Define a Pydantic model Task with title (str) and priority (int).
2. Create a POST endpoint at /create-task.
3. Use the Swagger UI (/docs) to send a JSON body to this endpoint and see
the validation in action.
Lab 1: The "Status Checker" API (Solution)

This exercise teaches you how to initialize the FastAPI app and define a basic GET
endpoint.

Python
from fastapi import FastAPI

# 1. Initialize the app


app = FastAPI()

# 2. Define the GET endpoint


@[Link]("/status")
def get_status():
return {
"status": "online",
"version": "1.0",
"server": "Uvicorn"
}

# To run: uvicorn main:app --reload


Lab 2: Dynamic User Greeting (Solution)

This exercise demonstrates the difference between Path Parameters (in the URL)
and Query Parameters (after the ?).

Python
from fastapi import FastAPI

app = FastAPI()

@[Link]("/hello/{name}")
def greet_user(name: str, professional: bool = False):
# Logic based on the query parameter
if professional:
return {"greeting": f"Hello Mr./Ms. {[Link]()}"}

return {"greeting": f"Hey {name}!"}

# Example URL: [Link]


Lab 3: Task Creator (Solution)

This exercise uses Pydantic for data validation and demonstrates how to handle a
POST request body.

Python
from fastapi import FastAPI
from pydantic import BaseModel

app = FastAPI()

# 1. Define the Pydantic Model (Schema)


class Task(BaseModel):
title: str
priority: int # FastAPI will ensure this is an integer

# 2. Define the POST endpoint


@[Link]("/create-task")
async def create_task(task: Task):
# In a real app, you'd save this to a database or file here
return {
"message": "Task received successfully",
"data_received": task
}

Final Capstone Project Preview

You now have all the building blocks for the Automated Task API Capstone.
The final project will require you to:

1. FastAPI: Create endpoints to view and add tasks.


2. Pydantic: Validate task data.
3. Automation: Write a separate script that uses requests to fetch these tasks
and json/os to save them to a file every minute.
The Capstone project consists of two parts:

the Server (FastAPI) and the Client-Side Automation (Scripting).

Capstone Project: The Automated Task System

Part 1: The FastAPI Server ([Link])

This part manages the data and provides endpoints for the automation script to
interact with.

Python
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
from typing import List

app = FastAPI()

# Pydantic Model for Data Validation


class Task(BaseModel):
id: int
title: str
completed: bool = False

# In-memory "Database"
db = [
{"id": 1, "title": "Setup Python Environment", "completed": True},
{"id": 2, "title": "Build FastAPI Server", "completed": False}
]

@[Link]("/tasks", response_model=List[Task])
async def get_tasks():
return db

@[Link]("/tasks")
async def add_task(task: Task):
[Link]([Link]())
return {"message": "Task added successfully", "task": task}
Part 2: The Automation Script ([Link])

This script runs independently, fetches data from the server, and logs it to a file.

Python
import requests
import json
import time
import os
from datetime import datetime

API_URL = "[Link]
LOG_FILE = "task_backups.json"

def fetch_and_backup():
try:
# 1. Web Interaction: Get data from our API
response = [Link](API_URL)
response.raise_for_status()
tasks = [Link]()

# 2. Data Processing: Add metadata


backup_data = {
"timestamp": [Link]().strftime("%Y-%m-%d %H:%M:%S"),
"total_tasks": len(tasks),
"tasks": tasks
}

# 3. File Operations: Save to a JSON file


with open(LOG_FILE, "w") as f:
[Link](backup_data, f, indent=4)

print(f"[{backup_data['timestamp']}] Backup successful: {len(tasks)} tasks


saved.")

except Exception as e:
print(f"Automation Error: {e}")
# 4. Task Scheduling: Run every 60 seconds
if __name__ == "__main__":
print("Automation started. Press Ctrl+C to stop.")
while True:
fetch_and_backup()
[Link](60)

How to Run the Project

1. Start the Server: Open a terminal and run: uvicorn server:app --reload
2. Test the Server: Go to [Link] and try the POST method
to add a new task.
3. Start the Automation: Open a second terminal and run: python
[Link]
4. Verify: Check your folder for the task_backups.json file. It will update
every minute with the latest tasks from your API.

You might also like