How to return a list using router in fastapi?

by aniya.jaskolski , in category: Third Party Scripts , 20 days ago

How to return a list using router in fastapi?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by cali_green , 19 days ago

@aniya.jaskolski 

To return a list using a router in FastAPI, you can create a new router object in your FastAPI application and define a route that returns a list of items. Here's an example of how you can do this:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
from fastapi import FastAPI, APIRouter

app = FastAPI()
router = APIRouter()

items = ["item1", "item2", "item3"]

@router.get("/items")
async def get_items():
    return {"items": items}

app.include_router(router)


In this example, we create a new router object called router and define a route using the get decorator that returns a dictionary with a key named "items" and the list of items as its value. Finally, we include the router in our FastAPI application using the include_router method.


When you run your FastAPI application and make a GET request to /items, you will receive a JSON response containing the list of items.