'FastApi urls path and 2 values into a query

im using FastApi and get some troubles with url. i have a root url

 @app.get("/myurl")

http://host/myurl and http://host/myurl?id=2 and here function returns all info from needed table.

on url like http://host/myurl?id=2&type=3 i need to get another query from table. how i need to create function because now this http://host/myurl?id=2 overlapping this function http://host/myurl?id=2&type=3

how i can use multiple urls with different values in it in fastapi?

and i want to know how to make url like http://host/myurl?id=2&type=3,2 to return result from table for two types (query example is SELECT * from mytable WHERE id=%(id)s and type IN (1,2) but type IN (,) should be parameters which i need to inpout



Solution 1:[1]

how i can use multiple urls with different values in it in fastapi?

As far as I know, you can't. But fortunately, you don't need to. What you can do is define only one route ("/myurl") with both parameters id and type, and set the second as optional. Then, if you don't receive type, you process a different query.

By the way, don't use id and type as parameter names, that will mess with the name of the in-built function id()and type().

Here a working example:

from fastapi import FastAPI, Query


app = FastAPI()


@app.get("/myurl")
async def my_url(my_id: int = Query(...), my_type: int = Query(None)):

    if my_type:
        return f"You gave an id ({my_id}) and a type ({my_type})."

    return f"You gave only an id ({my_id}) but no type."

i want to know how to make url like http://host/myurl?id=2&type=3,2

Not sure you can do it at all. What you can do is add the type parameter several times, like this:

http://host/myurl?my_id=2&my_type=3&my_type=2

In this case, you need to slightly change your code:

from fastapi import FastAPI, Query
from typing import List


app = FastAPI()


@app.get("/myurl")
async def my_url(my_id: int = Query(...), my_type: List[int] = Query(None)):

    if my_type:
        if len(my_type) > 1:
            return f"You gave an id ({my_id}) and a list of types ({my_type})."
        else:
            return f"You gave an id ({my_id}) and a type ({my_type})."

    return f"You gave only an id ({my_id}) but no type."

Note that you'll always receive my_type as a list then, even if you pass it only one time.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 ye olde noobe