Skip to content

Shreya4225/FastApi_basics

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

6 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

🧠 FastAPI β€” Quick Summary

πŸš€ Overview

FastAPI is a modern, high-performance web framework for building RESTful APIs with Python 3.7+.
Built on Starlette (for web parts) and Pydantic (for data validation).
Known for its speed, type hints, and automatic documentation.

βš™οΈ Key Features

  • Asynchronous support: Built-in support for async/await.
  • Data validation & serialization: Handled automatically via Pydantic models.
  • Automatic interactive docs: Swagger UI (/docs) and ReDoc (/redoc).
  • Dependency Injection: Clean handling of dependencies and middleware.
  • Type hinting: Ensures better autocompletion and error checking.
  • Performance: Comparable to Node.js and Go for API speed.

πŸ“˜ Basic Structure

from fastapi import FastAPI

app = FastAPI()

@app.get("/")
def home():
    return {"message": "Hello, FastAPI!"}

Run server:

uvicorn main:app --reload
Method Description
GET Retrieve data
POST Create new resource
PUT Update existing resource
DELETE Remove resource

🧱 Pydantic Models (Data Validation)

from pydantic import BaseModel

class Course(BaseModel):
    id: int
    name: str
    duration: int

Use it in endpoints:

@app.post("/courses")
def add_course(course: Course):
    return course

🧰 Useful Features

  • Path parameters: /courses/{id}
  • Query parameters: /courses?category=math
  • Request body: Automatic JSON parsing
  • Response models: Define output schemas
  • Exception handling: Use HTTPException for custom error responses
  • Middleware & CORS: Add easily for authentication or cross-origin support

Example – Using HTTPException:

from fastapi import HTTPException

@app.get("/courses/{id}")
def get_course(id: int):
    course = {"id": 1, "name": "Python"}  # example data
    if id != course["id"]:
        raise HTTPException(status_code=404, detail="Course not found")
    return course

🧾 Auto Documentation

πŸ“¦ Common Commands

pip install fastapi uvicorn
uvicorn main:app --reload

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages