Skip to content
The Chat Archive
gpt-3.5-turbo-0613· OpenAI WildChat-4.8M (AI2)

write python code for fast api

  1. User

    write python code for fast api

  2. Assistant

    Sure! Here's an example of a basic FastAPI code:

    from fastapi import FastAPI
    
    app = FastAPI()
    
    @app.get("/")
    async def root():
        return {"message": "Hello, World!"}
    
    @app.get("/items/{item_id}")
    async def read_item(item_id: int, q: str = None):
        return {"item_id": item_id, "q": q}
    
    if __name__ == "__main__":
        import uvicorn
        uvicorn.run(app, host="0.0.0.0", port=8000)
    

    This code creates a FastAPI instance (app), then defines two HTTP GET routes. The first route is the root route ("/") that returns a JSON response with the message "Hello, World!" when accessed. The second route ("/items/{item_id}") takes an integer item_id parameter and an optional query parameter q, and returns a JSON response containing the values of item_id and q.

    The if __name__ == "__main__" block at the end starts the server using uvicorn, which is an ASGI server for FastAPI. The server is set to run on the address "0.0.0.0" and port 8000. You can change these values to suit your needs.

    To run this code, make sure you have FastAPI and uvicorn installed (pip install fastapi uvicorn), save the code to a Python file (e.g., main.py), and run it using python main.py in your terminal.