Ojasa Mirai

Ojasa Mirai

FastAPI

Loading...

Learning Level

🟢 Beginner🔵 Advanced
🚀 What is FastAPI📚 Creating Your First API📚 Running the Server📚 HTTP Methods📚 API Endpoints📚 Request and Response📚 Documentation📚 Testing Basics
Fastapi/Api Basics/First Api

Creating Your First API âš¡

Let's build and run your first working FastAPI endpoint in just a few minutes.

Installation

Install FastAPI and Uvicorn:

pip install fastapi uvicorn

Create Your First Endpoint

Create `main.py`:

from fastapi import FastAPI

app = FastAPI()

@app.get("/")
async def root():
    return {"message": "Hello, World!"}

Run the Server

uvicorn main:app --reload

Visit `http://localhost:8000` in your browser. You'll see your JSON response!

Understanding the Code

ComponentMeaning
`app = FastAPI()`Creates the API application
`@app.get("/")`Creates a GET endpoint at root
`async def`Async function for concurrent requests
`return {...}`JSON response sent to client

Try Interactive Documentation

Visit `http://localhost:8000/docs` to see Swagger UI where you can:

  • View all endpoints
  • See request/response schemas
  • Test endpoints directly

Create More Endpoints

from fastapi import FastAPI
from pydantic import BaseModel

app = FastAPI()

class Item(BaseModel):
    name: str
    price: float

@app.get("/items")
async def list_items():
    return [{"id": 1, "name": "Item 1", "price": 10.0}]

@app.post("/items")
async def create_item(item: Item):
    return {"id": 2, **item.dict()}

@app.get("/items/{item_id}")
async def get_item(item_id: int):
    return {"id": item_id, "name": "Item", "price": 10.0}

Pydantic Models

Use Pydantic to define request/response structure:

from pydantic import BaseModel, Field

class User(BaseModel):
    name: str = Field(..., min_length=1, max_length=100)
    email: str
    age: int = Field(..., ge=0, le=150)
    is_active: bool = True

HTTP Methods

MethodPurposeExample
GETRetrieve dataList items
POSTCreate dataCreate new item
PUTReplace dataReplace entire item
DELETERemove dataDelete item
PATCHUpdate dataPartial update

Testing Your API

Use `curl` to test:

# GET request
curl http://localhost:8000/items/1

# POST request
curl -X POST http://localhost:8000/items \
  -H "Content-Type: application/json" \
  -d '{"name":"New Item","price":25.0}'

Key Takeaways

  • ✅ FastAPI requires minimal setup and code
  • ✅ `@app.get()`, `@app.post()` define endpoints
  • ✅ Return dictionaries or Pydantic models
  • ✅ Type hints enable automatic validation
  • ✅ Interactive docs at `/docs` help with testing

Resources

Python Docs

Ojasa Mirai

Master AI-powered development skills through structured learning, real projects, and verified credentials. Whether you're upskilling your team or launching your career, we deliver the skills companies actually need.

Learn Deep • Build Real • Verify Skills • Launch Forward

Courses

PythonFastapiReactJSCloud

© 2026 Ojasa Mirai. All rights reserved.

TwitterGitHubLinkedIn