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
Okay, let's spin up a basic FastAPI application with several useful common endpoints.
This will include:
- Health Check (
/): A simple endpoint to check if the API is running. - Echo (
/echo): An endpoint to echo back a message, demonstrating query parameters. - Echo with Body (
/echo_body): An endpoint to echo back structured data from a request body, demonstrating Pydantic models. - UUID Generator (
/generate/uuid): Generates a new UUID. - Current UTC Time (
/time): Returns the current UTC timestamp. - Simple Calculator (
/calculate/add): Adds two numbers provided as path parameters. - Simulated Error (
/fail): Demonstrates how to return an HTTP error. - Configuration Info (
/config): Returns some mock application configuration.
Step 1: Set up your environment
First, make sure you have Python installed. Then, create a new directory for your project, navigate into it, and install FastAPI and Uvicorn:
mkdir fastapi_utils cd fastapi_utils pip install fastapi "uvicorn[standard]"Step 2: Create the FastAPI Application File
Create a file named
main.py(or any other name you prefer) in yourfastapi_utilsdirectory and paste the following code:from fastapi import FastAPI, HTTPException, Query, status from pydantic import BaseModel import uuid from datetime import datetime, timezone # 1. Initialize FastAPI app app = FastAPI( title="Basic FastAPI Utility API", description="A simple API demonstrating basic FastAPI features and useful utility functions.", version="1.0.0", ) # --- Pydantic Models for Request/Response Bodies --- class EchoRequestBody(BaseModel): """ Model for the request body of the /echo_body endpoint. """ message: str uppercase: bool = False # Optional parameter, defaults to False class EchoResponse(BaseModel): """ Model for the response body of the /echo and /echo_body endpoints. """ received_input: str processed_message: str timestamp: datetime input_type: str # --- API Endpoints --- # 2. Health Check / Root Endpoint @app.get( "/", summary="Health Check", response_description="Basic API status message" ) async def read_root(): """ A simple endpoint to confirm the API is running and accessible. """ return {"message": "Welcome to the Basic FastAPI Utility API!", "status": "online"} # 3. Echo Endpoint (using Query Parameters) @app.get( "/echo/", response_model=EchoResponse, summary="Echo a message from query parameter", response_description="The original and processed message, along with a timestamp" ) async def echo_message( message: str = Query(..., description="The message to be echoed back."), capitalize: bool = Query(False, description="Set to true to capitalize the message.") ): """ Echoes back a message provided as a query parameter. Optionally capitalizes the message. """ processed_msg = message.upper() if capitalize else message return EchoResponse( received_input=message, processed_message=processed_msg, timestamp=datetime.now(timezone.utc), input_type="query_parameter" ) # 4. Echo Endpoint (using Request Body) @app.post( "/echo_body/", response_model=EchoResponse, summary="Echo a message from request body", response_description="The original and processed message from the request body, with a timestamp" ) async def echo_body(request: EchoRequestBody): """ Echoes back a message provided in the request body. Expects a JSON object with a 'message' string and an optional 'uppercase' boolean. """ processed_msg = request.message.upper() if request.uppercase else request.message return EchoResponse( received_input=request.message, processed_message=processed_msg, timestamp=datetime.now(timezone.utc), input_type="request_body" ) # 5. UUID Generator @app.get( "/generate/uuid/", summary="Generate a new UUID", response_description="A newly generated UUID v4" ) async def generate_new_uuid(): """ Generates and returns a new universally unique identifier (UUID v4). """ return {"uuid": str(uuid.uuid4())} # 6. Current UTC Time @app.get( "/time/", summary="Get current UTC time", response_description="The current timestamp in UTC" ) async def get_current_time(): """ Returns the current Coordinated Universal Time (UTC) in ISO format. """ return {"current_utc_time": datetime.now(timezone.utc).isoformat()} # 7. Simple Calculator - Add @app.get( "/calculate/add/{num1}/{num2}", summary="Add two numbers", response_description="The sum of the two provided numbers" ) async def add_numbers(num1: float, num2: float): """ Adds two floating-point numbers provided as path parameters. """ return {"num1": num1, "num2": num2, "sum": num1 + num2} # 8. Simulated Error @app.get( "/fail/", summary="Simulate an internal server error", response_description="An error message indicating a simulated failure" ) async def simulate_failure(): """ This endpoint intentionally raises an HTTP 500 Internal Server Error to demonstrate error handling. """ raise HTTPException( status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail="This is a simulated internal server error." ) # 9. Configuration Info @app.get( "/config/", summary="Get application configuration", response_description="Basic application configuration details" ) async def get_app_config(): """ Returns some basic, hardcoded application configuration details. In a real application, this would load from environment variables or a config file. """ return { "app_name": app.title, "version": app.version, "environment": "development", "debug_mode": True, "api_docs_url": "/docs" } # --- Main entry point for running with Uvicorn --- if __name__ == "__main__": import uvicorn # This ensures the app runs when executing `python main.py` directly # The default host is 127.0.0.1 and port is 8000 uvicorn.run("main:app", host="0.0.0.0", port=8000, reload=True)Step 3: Run the FastAPI Application
Open your terminal in the
fastapi_utilsdirectory and run:uvicorn main:app --reload --host 0.0.0.0 --port 8000main:app: Tells Uvicorn to look for theappobject inmain.py.--reload: Automatically reloads the server on code changes (great for development).--host 0.0.0.0: Makes the server accessible from other devices on your network (useful if you're testing from a different machine or within a Docker container). You can omit this if only running locally.--port 8000: Specifies the port to run on.
You should see output similar to this:
INFO: Will watch for changes in these directories: ['/path/to/fastapi_utils'] INFO: Uvicorn running on http://0.0.0.0: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: Test Your Endpoints
Open your web browser or use a tool like
curlor Postman/Insomnia to test the endpoints.-
Swagger UI (Interactive Docs): Open your browser to:
http://localhost:8000/docsYou'll see the automatically generated interactive API documentation, where you can test all the endpoints directly. -
Health Check:
- Browser:
http://localhost:8000/ curl:curl http://localhost:8000/- Expected Output:
{"message":"Welcome to the Basic FastAPI Utility API!","status":"online"}
- Browser:
-
Echo (Query Parameters):
- Browser:
http://localhost:8000/echo/?message=hello_world&capitalize=true curl:curl "http://localhost:8000/echo/?message=test_message&capitalize=false"- Expected Output: JSON containing your message, capitalized or not.
- Browser:
-
Echo (Request Body):
- Method: POST
- URL:
http://localhost:8000/echo_body/ - Body (JSON):
{ "message": "This is a body message", "uppercase": true } - Expected Output: JSON containing your message from the body, capitalized or not.
-
UUID Generator:
- Browser:
http://localhost:8000/generate/uuid/ curl:curl http://localhost:8000/generate/uuid/- Expected Output:
{"uuid":"some-random-uuid-string"}
- Browser:
-
Current UTC Time:
- Browser:
http://localhost:8000/time/ curl:curl http://localhost:8000/time/- Expected Output:
{"current_utc_time":"2023-10-27T10:30:00.123456+00:00"}(time will vary)
- Browser:
-
Simple Calculator (Add):
- Browser:
http://localhost:8000/calculate/add/10.5/20 curl:curl http://localhost:8000/calculate/add/5/3- Expected Output:
{"num1":5.0,"num2":3.0,"sum":8.0}
- Browser:
-
Simulated Error:
- Browser:
http://localhost:8000/fail/ curl:curl -v http://localhost:8000/fail/(use-vto see HTTP status code)- Expected Output: HTTP Status
500 Internal Server Error, with JSON body:{"detail":"This is a simulated internal server error."}
- Browser:
-
Configuration Info:
- Browser:
http://localhost:8000/config/ curl:curl http://localhost:8000/config/- Expected Output:
{"app_name":"Basic FastAPI Utility API","version":"1.0.0","environment":"development","debug_mode":true,"api_docs_url":"/docs"}
- Browser:
This setup provides a solid foundation for a basic FastAPI application, demonstrating various core features and useful utility endpoints.
- Health Check (
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.