Skip to content
TheChatArchiveThe Chat Archive
Geminigemini-2.5-flash· GoogleHugging Face LMArena Human Preference 140K

spin up a basic fastapi endpoint that offers some useful basic functions

From a Chatbot Arena battleThe same person sent this prompt to two anonymous models at once. Compare it with Geminigemini-2.5-pro’s answer.
  1. User

    spin up a basic fastapi endpoint that offers some useful basic functions

  2. Gemini Assistant

    Okay, let's spin up a basic FastAPI application with several useful common endpoints.

    This will include:

    1. Health Check (/): A simple endpoint to check if the API is running.
    2. Echo (/echo): An endpoint to echo back a message, demonstrating query parameters.
    3. Echo with Body (/echo_body): An endpoint to echo back structured data from a request body, demonstrating Pydantic models.
    4. UUID Generator (/generate/uuid): Generates a new UUID.
    5. Current UTC Time (/time): Returns the current UTC timestamp.
    6. Simple Calculator (/calculate/add): Adds two numbers provided as path parameters.
    7. Simulated Error (/fail): Demonstrates how to return an HTTP error.
    8. 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 your fastapi_utils directory 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_utils directory and run:

    uvicorn main:app --reload --host 0.0.0.0 --port 8000
    
    • main:app: Tells Uvicorn to look for the app object in main.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 curl or Postman/Insomnia to test the endpoints.

    1. Swagger UI (Interactive Docs): Open your browser to: http://localhost:8000/docs You'll see the automatically generated interactive API documentation, where you can test all the endpoints directly.

    2. Health Check:

      • Browser: http://localhost:8000/
      • curl: curl http://localhost:8000/
      • Expected Output: {"message":"Welcome to the Basic FastAPI Utility API!","status":"online"}
    3. 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.
    4. 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.
    5. UUID Generator:

      • Browser: http://localhost:8000/generate/uuid/
      • curl: curl http://localhost:8000/generate/uuid/
      • Expected Output: {"uuid":"some-random-uuid-string"}
    6. 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)
    7. 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}
    8. Simulated Error:

      • Browser: http://localhost:8000/fail/
      • curl: curl -v http://localhost:8000/fail/ (use -v to see HTTP status code)
      • Expected Output: HTTP Status 500 Internal Server Error, with JSON body: {"detail":"This is a simulated internal server error."}
    9. 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"}

    This setup provides a solid foundation for a basic FastAPI application, demonstrating various core features and useful utility endpoints.

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.