Introduction to FastAPI
FastAPI is a modern, fast (high-performance) web framework for building APIs with
Python 3.7+ based on standard type hints.
Agenda
• What is FastAPI?
• Why use FastAPI?
• Required modules and installation
• Creating a basic FastAPI application
• Building a CRUD API
• Running and testing the app
© 2024 Miracle Software Systems, Inc. | #2
What is FastAPI
• FastAPI is a modern Python web framework for building APIs quickly and
efficiently. It leverages Python type hints to provide automatic request
validation and documentation. Built on Starlette (for web handling) and
Pydantic (for data validation), it's highly performant. FastAPI automatically
generates interactive API docs using Swagger UI. It supports asynchronous
programming out of the box for high-concurrency applications. Ideal for
building RESTful APIs, microservices, and backend services with minimal
code.
© 2024 Miracle Software Systems, Inc. | #3
Why use FastAPI
• High Performance: Comparable to Node.js and Go thanks to ASGI and async
support(One of the fastest Python frameworks available).
• Automatic Validation: Uses Python type hints and Pydantic for input/output
validation.
• Interactive Docs: Auto-generates Swagger documentation for your API.
• Modern Features: Built-in support for async, dependency injection, and
OAuth2.
• Clean Code: Type-hinted, readable, and maintainable code structure.
• Faster Development: Less boilerplate and immediate feedback with interactive
docs.
© 2024 Miracle Software Systems, Inc. | #4
Required modules and installation
• fastapi – Core framework
• uvicorn – ASGI server to run FastAPI
• Command to install FastAPI:
• pip install fastapi uvicorn
• pydantic – For data validation
• typing – Built-in Python types for hints
© 2024 Miracle Software Systems, Inc. | #5
Creating a Basic FastAPI App
# main.py
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
def read_root():
return {"message": "Hello, FastAPI!"}
Run it using uvicorn:
uvicorn main:app --reload
© 2024 Miracle Software Systems, Inc. | #6
Building a CRUD API
# Import required modules from FastAPI and related packages
from fastapi import FastAPI, HTTPException, Request # FastAPI core, HTTP exceptions, and request object
from fastapi.middleware.cors import CORSMiddleware # For enabling CORS (Cross-Origin Resource
Sharing)
from pydantic import BaseModel # Used for request validation and data modeling
from typing import List, Optional # Type hints for lists and optional values
import uvicorn # ASGI server to run FastAPI apps
from fastapi.staticfiles import StaticFiles # To serve static files like JS/CSS/images
from fastapi.responses import FileResponse # To return files as responses
from dotenv import load_dotenv # To load environment variables from a `.env` file
import os # To access environment variables
© 2024 Miracle Software Systems, Inc. | #7
# Load environment variables from the .env file into the system
load_dotenv()
# Initialize the FastAPI application
app = FastAPI()
# Add CORS middleware to allow cross-origin requests
# This setup allows *all* origins, which is okay for development
# In production, restrict `allow_origins` to specific domains
app.add_middleware(
CORSMiddleware,
allow_origins=["*"], # Allow all origins
allow_credentials=True, # Allow cookies and authentication headers
allow_methods=["*"], # Allow all HTTP methods: GET, POST, PUT, DELETE, etc.
allow_headers=["*"], # Allow all headers
)
© 2024 Miracle Software Systems, Inc. | #8
# Define a data model for the items using Pydantic
# This model defines the structure of request/response objects
class Item(BaseModel):
id: int # Required integer ID
name: str # Required name string
description: Optional[str] = None # Optional description string
# Simulate a database using a Python dictionary
# Keys will be item IDs, and values will be `Item` objects
items_db = {}
# Read the PROJECT_ID from environment variables
project_id = os.environ["PROJECT_ID"]
© 2024 Miracle Software Systems, Inc. | #9
# Define a route to get all items
@app.get("/items/", response_model=List[Item])
def get_items():
return list(items_db.values()) # Return all items in the "database" as a list
# Define a route to get a specific item by ID
@app.get("/items/{item_id}", response_model=Item)
def get_item(item_id: int):
if item_id not in items_db: # Check if item exists
raise HTTPException(status_code=404, detail="Item not found") # Return 404 if not found
return items_db[item_id] # Return the requested item
© 2024 Miracle Software Systems, Inc. | #10
# Define a route to create a new item
@app.post("/items/", response_model=Item)
def create_item(item: Item):
if item.id in items_db: # Check if item already exists
raise HTTPException(status_code=400, detail="Item already exists") # return 400 if duplicate
items_db[item.id] = item # Save the item to the "database"
return item # Return the created item
# Define a route to update an existing item
@app.put("/items/{item_id}", response_model=Item)
def update_item(item_id: int, item: Item):
if item_id not in items_db: # Check if item exists
raise HTTPException(status_code=404, detail="Item not found") # return 404 if not found
items_db[item_id] = item # Update the item with new data
return item # Return the updated item
© 2024 Miracle Software Systems, Inc. | #11
# Define a route to delete an item by ID
@app.delete("/items/{item_id}")
def delete_item(item_id: int):
if item_id not in items_db: # Check if item exists
raise HTTPException(status_code=404, detail="Item not found") # Return 404 if not found
del items_db[item_id] # Remove item from the "database"
return {"detail": "Item deleted successfully"} # Return confirmation message
# Entry point for running the app directly using `python script.py`
if __name__ == "__main__":
# Start the FastAPI app using Uvicorn server
uvicorn.run(app, host="0.0.0.0", port=8000)
© 2024 Miracle Software Systems, Inc. | #12
Running and testing the app
Command to run the app (with auto-reload during development):
uvicorn main:app --reload
main: the filename (without .py)
app: the FastAPI instance name inside the file
--reload: enables auto-reloading when code changes
Access the app in your browser
Open a browser and go to:
• Main endpoint: http://127.0.0.1:8000/
© 2024 Miracle Software Systems, Inc. | #13
THANK YOU
www.miraclesoft.com