spin up a basic fastapi endpoint that offers some useful basic functions
- User
spin up a basic fastapi endpoint that offers some useful basic functions
Assistant
Of course! Here is a well-commented, basic but functional FastAPI application that demonstrates several common and useful features.
This example includes:
- A basic root endpoint (
/). - An endpoint with path and query parameters.
- An endpoint that accepts a POST request with a JSON body, validated by Pydantic.
- A set of "utility" endpoints grouped under a
/toolsprefix using anAPIRouter. These perform simple, useful tasks like hashing text and generating UUIDs. - Automatic, interactive API documentation (the best part of FastAPI!).
Step 1: The Python Code
Save this code in a file named
main.py.# main.py import hashlib import uuid from datetime import datetime, timezone from typing import Optional from fastapi import FastAPI, APIRouter, Body from pydantic import BaseModel, Field # --- 1. Pydantic Models for Request/Response Data --- # Pydantic models define the structure, types, and validation for your data. class User(BaseModel): """A model representing a user, used for the POST request.""" username: str = Field( ..., # The ellipsis (...) means this field is required min_length=3, max_length=50, example="john_doe" ) email: str = Field( ..., example="johndoe@example.com" ) class HashRequest(BaseModel): """Model for the hashing tool request.""" text: str = Field(..., example="hello fastapi") algorithm: str = Field("sha256", example="sha256") # --- 2. FastAPI App Initialization --- # This is the main entry point of your application. # The metadata here will be displayed in the automatic docs. app = FastAPI( title="Basic Functions API", description="A collection of useful, basic API endpoints.", version="1.0.0", ) # --- 3. Using APIRouter for Better Organization --- # APIRouter helps organize endpoints into logical groups. # Here, we create a router for our "tools". tools_router = APIRouter( prefix="/tools", # All routes in this router will start with /tools tags=["Tools"], # They will be grouped under "Tools" in the docs ) # --- 4. Defining API Endpoints --- # A. Main application endpoints @app.get("/", tags=["General"]) def read_root(): """ A simple welcome message for the root URL. """ return {"message": "Welcome to the Basic Functions API!"} @app.get("/items/{item_id}", tags=["General"]) def read_item(item_id: int, q: Optional[str] = None): """ Demonstrates path parameters (`item_id`) and optional query parameters (`q`). - `item_id` is an integer and is required. - `q` is an optional string. """ response = {"item_id": item_id} if q: response.update({"q": q}) return response @app.post("/users/", response_model=User, tags=["General"]) def create_user(user: User): """ Demonstrates a POST request with a request body. FastAPI uses the `User` Pydantic model to: 1. Validate the incoming JSON. 2. Parse it into a Python object (`user`). 3. Document the expected request body format in the API docs. """ # In a real app, you would save the user to a database. # Here, we just return the data that was sent. return user # B. Endpoints attached to the "tools" router @tools_router.post("/hash") def create_hash(data: HashRequest): """ Hashes the provided text using the specified algorithm (defaults to sha256). """ try: hasher = hashlib.new(data.algorithm) hasher.update(data.text.encode('utf-8')) return { "original_text": data.text, "algorithm": data.algorithm, "hashed_value": hasher.hexdigest(), } except ValueError: return {"error": f"Unsupported algorithm: {data.algorithm}"} @tools_router.get("/uuid") def generate_uuid(): """ Generates and returns a random Version 4 UUID. """ return {"uuid": str(uuid.uuid4())} @tools_router.get("/time") def get_current_time(): """ Returns the current server time in UTC with ISO 8601 format. """ return {"utc_time": datetime.now(timezone.utc).isoformat()} # --- 5. Include the router in the main app --- # This makes all the routes from `tools_router` available in our application. app.include_router(tools_router)
Step 2: Install Dependencies
You'll need
fastapiitself and an ASGI server likeuvicornto run it. Thestandardoption for uvicorn includes performance-enhancing libraries.Open your terminal and run:
pip install fastapi "uvicorn[standard]"
Step 3: Run the API Server
In your terminal, navigate to the directory where you saved
main.pyand run the following command:uvicorn main:app --reloadmain: The filemain.py.app: TheFastAPIobjectappyou created insidemain.py.--reload: This makes the server automatically restart when you save changes to the code, which is great for development.
You should see output like this, indicating the server is running:
INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) INFO: Started reloader process [xxxxx] INFO: Started server process [xxxxx] INFO: Waiting for application startup. INFO: Application startup complete.
Step 4: Use Your API
Your API is now live at
http://127.0.0.1:8000.Option A: Use the Interactive Docs (Recommended)
This is the killer feature of FastAPI. Open your web browser and go to:
http://127.0.0.1:8000/docsYou'll see a beautiful, interactive API documentation page where you can:
- See all your endpoints, grouped by tags.
- Expand each one to see details about parameters, request bodies, and responses.
- Click "Try it out" to test each endpoint directly from your browser!
Option B: Use
curlor any API client (like Postman)You can also interact with your endpoints from the command line.
1. Get the root message:
curl http://127.0.0.1:8000/2. Get an item with a query parameter:
curl "http://127.0.0.1:8000/items/42?q=hello"3. Create a new user (POST request):
curl -X POST "http://127.0.0.1:8000/users/" \ -H "Content-Type: application/json" \ -d '{"username": "testuser", "email": "test@example.com"}'4. Hash some text:
curl -X POST "http://127.0.0.1:8000/tools/hash" \ -H "Content-Type: application/json" \ -d '{"text": "fastapi is awesome"}'5. Generate a UUID:
curl http://127.0.0.1:8000/tools/uuid- A basic root endpoint (
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.