write python code for fast api
- User
write python code for fast api
- 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 integeritem_idparameter and an optional query parameterq, and returns a JSON response containing the values ofitem_idandq.The
if __name__ == "__main__"block at the end starts the server usinguvicorn, 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 usingpython main.pyin your terminal.