FastAPI Fundamentals

Loading concept...

FastAPI Fundamentals: Your Super-Fast Restaurant Kitchen 🍳

Imagine you’re building a super-fast restaurant kitchen that takes orders from customers and serves delicious food in seconds. That’s exactly what FastAPI does for web applications!


What is FastAPI?

Think of FastAPI like a magical kitchen assistant that:

  • Takes orders (requests) from customers super fast
  • Knows exactly what ingredients (data) are needed
  • Serves food (responses) lightning quick
  • Never makes mistakes because it checks everything twice!

The Real Story

FastAPI is a modern Python framework for building APIs (ways for apps to talk to each other). It’s like giving your Python code superpowers to talk to the internet!

Why “Fast” in the name?

  1. Fast to run - One of the fastest Python frameworks
  2. Fast to code - Less typing, more doing
  3. Fast to learn - Super simple to understand
# This is ALL you need to create an API!
from fastapi import FastAPI
app = FastAPI()

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

That’s it! 4 lines and you have a working API! 🎉


Starlette and Pydantic Basics

FastAPI has two best friends that make it powerful:

🌟 Starlette - The Speed Machine

Think of Starlette like the engine of a race car. You don’t see it, but it makes everything go FAST!

graph TD A[Your FastAPI Code] --> B[Starlette Engine] B --> C[Super Fast Web Server] C --> D[Happy Users!]

What Starlette does:

  • Handles all the web stuff (routes, requests, responses)
  • Makes your API run at lightning speed
  • You don’t need to worry about it - FastAPI uses it automatically!

📦 Pydantic - The Data Guardian

Pydantic is like a strict but friendly security guard for your data:

from pydantic import BaseModel

# Define what a "User" looks like
class User(BaseModel):
    name: str      # Must be text
    age: int       # Must be a number
    email: str     # Must be text

# Pydantic checks if data is correct!
user = User(name="Sam", age=10, email="sam@email.com")
# ✅ This works!

user = User(name="Sam", age="ten", email="sam@email.com")
# ❌ Error! "ten" is not a number!

Pydantic’s job:

  • Checks if data is the right type
  • Converts data when possible (like “10” → 10)
  • Tells you exactly what’s wrong if data is bad

FastAPI Setup and Installation

Let’s set up your magical kitchen! It’s as easy as 1-2-3.

Step 1: Install FastAPI

Open your terminal (the black window where you type commands) and type:

pip install fastapi

Step 2: Install Uvicorn

Uvicorn is like the power plug that makes your API run:

pip install uvicorn

All Together (One Command!)

Want both at once? Easy!

pip install fastapi uvicorn
graph TD A[pip install fastapi] --> B[FastAPI Ready!] C[pip install uvicorn] --> D[Server Ready!] B --> E[You're All Set! 🎉] D --> E

That’s it! You now have everything needed to build APIs.


Running FastAPI Application

Time to turn on your kitchen! Let’s make your first API run.

Step 1: Create Your File

Make a file called main.py:

from fastapi import FastAPI

app = FastAPI()

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

Step 2: Run It!

In your terminal, type:

uvicorn main:app --reload

What this means:

  • main = your file name (main.py)
  • app = your FastAPI app variable
  • --reload = auto-restart when you change code

You’ll See This:

INFO:     Uvicorn running on http://127.0.0.1:8000
INFO:     Application startup complete.

🎉 Your API is now running! Open your browser and go to http://127.0.0.1:8000

graph TD A[Create main.py] --> B[Write FastAPI Code] B --> C[Run: uvicorn main:app --reload] C --> D[Visit localhost:8000] D --> E[See Your API! 🎉]

First Endpoint Creation

An endpoint is like a menu item in your restaurant. Each endpoint does one thing!

The GET Endpoint - Reading Data

from fastapi import FastAPI

app = FastAPI()

# This is an endpoint!
@app.get("/hello")
def say_hello():
    return {"message": "Hello there!"}

# Another endpoint!
@app.get("/goodbye")
def say_goodbye():
    return {"message": "See you later!"}

Understanding the Magic

@app.get("/hello")  # 👈 The decorator
def say_hello():    # 👈 The function
    return {...}    # 👈 What you send back
Part What It Does
@app.get Listen for GET requests
"/hello" The URL path
def say_hello() What to do
return {...} Send this back

Adding Parameters - Make It Personal!

@app.get("/hello/{name}")
def say_hello(name: str):
    return {"message": f"Hello, {name}!"}

Visit http://127.0.0.1:8000/hello/Sam and you’ll see:

{"message": "Hello, Sam!"}
graph TD A[User visits /hello/Sam] --> B[FastAPI catches it] B --> C[Runs say_hello with name=Sam] C --> D[Returns: Hello, Sam!]

Automatic API Documentation

Here’s the coolest magic trick - FastAPI writes documentation FOR YOU!

Swagger UI - Interactive Docs

Just add /docs to your URL:

http://127.0.0.1:8000/docs

You’ll see a beautiful page where you can:

  • 👀 See all your endpoints
  • 🧪 Test them right in the browser
  • 📖 Read what each one does

ReDoc - Pretty Docs

Want a different style? Try:

http://127.0.0.1:8000/redoc

This gives you cleaner, more readable documentation.

It Updates Automatically!

@app.get("/items/{item_id}")
def get_item(item_id: int, details: bool = False):
    """
    Get an item by its ID.

    - **item_id**: The unique ID of the item
    - **details**: Include extra details?
    """
    return {"item_id": item_id}

That comment (docstring) appears in your docs! No extra work!

graph TD A[Write Code] --> B[FastAPI Reads It] B --> C[Creates /docs Page] B --> D[Creates /redoc Page] C --> E[You Test & Share!] D --> E

API Metadata Configuration

Make your API look professional with custom information!

Basic Metadata

from fastapi import FastAPI

app = FastAPI(
    title="My Awesome API",
    description="This API does amazing things!",
    version="1.0.0"
)

Full Configuration Example

app = FastAPI(
    title="Super Store API",
    description="""
    🛒 **Super Store API** helps you manage products.

    ## Features
    * Add products
    * Get product details
    * Update prices
    """,
    version="2.0.0",
    contact={
        "name": "Support Team",
        "email": "help@superstore.com",
    },
    license_info={
        "name": "MIT License",
    }
)

Organize with Tags

Group your endpoints like chapters in a book:

@app.get("/users/", tags=["Users"])
def get_users():
    return [{"name": "Sam"}]

@app.get("/items/", tags=["Items"])
def get_items():
    return [{"item": "Apple"}]

Now your docs show organized sections!

graph TD A[FastAPI App] --> B[title: Your API Name] A --> C[description: What it does] A --> D[version: 1.0.0] A --> E[tags: Organize endpoints] B --> F[Professional Looking Docs!] C --> F D --> F E --> F

🎯 Quick Summary

Concept What It Is Example
FastAPI Fast Python web framework FastAPI()
Starlette The speed engine underneath (automatic)
Pydantic Data validation guardian BaseModel
Installation Get FastAPI ready pip install fastapi uvicorn
Running Start your server uvicorn main:app --reload
Endpoint A URL that does something @app.get("/hello")
Auto Docs Free documentation! /docs and /redoc
Metadata Customize your API info title, description, version

🚀 You Did It!

You now understand the foundations of FastAPI! You learned:

✅ What FastAPI is and why it’s awesome ✅ How Starlette and Pydantic help ✅ How to install everything ✅ How to run your first API ✅ How to create endpoints ✅ How to use automatic documentation ✅ How to configure your API metadata

Next step? Start building your own APIs and see the magic happen! 🎉

Loading story...

No Story Available

This concept doesn't have a story yet.

Story Preview

Story - Premium Content

Please sign in to view this concept and start learning.

Upgrade to Premium to unlock full access to all content.

Interactive Preview

Interactive - Premium Content

Please sign in to view this concept and start learning.

Upgrade to Premium to unlock full access to all content.

No Interactive Content

This concept doesn't have interactive content yet.

Cheatsheet Preview

Cheatsheet - Premium Content

Please sign in to view this concept and start learning.

Upgrade to Premium to unlock full access to all content.

No Cheatsheet Available

This concept doesn't have a cheatsheet yet.

Quiz Preview

Quiz - Premium Content

Please sign in to view this concept and start learning.

Upgrade to Premium to unlock full access to all content.

No Quiz Available

This concept doesn't have a quiz yet.