IT-INFO

Where IT meets innovation, IT-INFO lights the path to technological brilliance

Getting Started with FastAPI

Getting Started with FastAPI

FastAPI is a modern, fast (high-performance), web framework for building APIs with Python 3.7+ based on standard Python type hints.

Installation

To get started with FastAPI, you need to have Python 3.7+ installed. You can install FastAPI and an ASGI server using pip.

pip install fastapi
pip install "uvicorn[standard]"

Creating Your First FastAPI App

Let's create a simple FastAPI application. Create a new file named main.py and add the following content:

from fastapi import FastAPI

app = FastAPI()

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

@app.get("/items/{item_id}")
def read_item(item_id: int, q: str = None):
    return {"item_id": item_id, "q": q}

Running Your FastAPI App

To run the FastAPI application, use the uvicorn command:

uvicorn main:app --reload

Open your browser and go to http://127.0.0.1:8000. You should see a JSON response:

{"Hello": "World"}

FastAPI automatically generates an interactive API documentation. You can access it at http://127.0.0.1:8000/docs.

Creating API Endpoints

FastAPI allows you to easily create different types of API endpoints. For example, to create a POST endpoint, you can add the following code to your main.py:

from pydantic import BaseModel

class Item(BaseModel):
    name: str
    description: str = None
    price: float
    tax: float = None

@app.post("/items/")
def create_item(item: Item):
    return item

Conclusion

In this guide, you've learned how to install FastAPI, create a simple FastAPI application, and run it using Uvicorn. FastAPI makes it easy to build and deploy high-performance APIs with minimal effort. For more advanced features and customization, refer to the official FastAPI documentation.

Created on Aug. 7, 2024, 12:17 p.m.