[PYTHON] FastAPI Tutorial Memo Part 3 Query Parameters

Introduction

FastAPI Souce: https://github.com/tiangolo/fastapi FastAPI Document: https://fastapi.tiangolo.com

Target: Query Parameters

FastAPI tutorial notes. Basically, I refer to the official tutorial of Fast API, but I omit some parts or change the order for my own learning. Please refer to the official documentation for the correct and detailed information.

Since I am a beginner of Web & Python and rely on Google and DeepL for translation, I would appreciate it if you could point out any mistakes.

Click here for previous notes

-FastAPI Tutorial Memo Part 1 Installation -FastAPI Tutorial Memo Part 2 Path Parameters

Development environment

Ubuntu 20.04 LTS Python 3.8.2 pipenv 2018.11.26

Target

--Understanding how to use ** Query Parameter ** in FastAPI

procedure

Intro Last time (FastAPI Tutorial Memo 2 Path Parameters), I learned how to pass ** Path Parameters ** as function parameters. This time I would like to learn how to pass ** Query parameters **.

In FastAPI, if you declare a parameter that is not a Path parameter as a function argument, it will be automatically interpreted as a ** Query parameter **. Check the code below.

main.py


from fastapi import FastAPI

app = FastAPI()

fake_items_db = [{"item_name": "Foo"}, {"item_name": "Bar"}, {"item_name": "Baz"}]


@app.get("/items/")
async def read_item(skip: int = 0, limit: int = 10):    # <-Query parameter is specified.
    return fake_items_db[skip : skip + limit]

In HTTP URIs, ** queries ** are basically expressed by connecting key and value pairs that follow ? with =. If you specify more than one, separate the URIs with &. If you want to match the above code, for example, the following URL is assumed:

http://127.0.0.1:8000/items/?skip=0&limit=10

The ** Query parameter ** in this case is

--skip with a value of 0 --limit with a value of 10

Are passed to the function.

Since these are part of the URL, they should normally be interpreted as strings (str). However, in the above code, when specifying a parameter as an argument, it is declared with the Python type ʻint type, so the parameter is converted and verified to the ʻint type.

This means that the following benefits applied with the ** Path parameter ** also apply to the ** Query parameter **.

--Editor support --Data "parsing" (analysis) --Data verification --Automatic documentation

In addition, these advantages are supported not only by Path and Query but also by various parameters handled by Fast API.

Defaults

The ** Query parameter ** is not fixed by the URI path, but is an optional setting, so you can specify the default value.

In the code above, you can see that the default values are skip = 0 and limit = 10. So a URL like this:

http://127.0.0.1:8000/items/

When accessed from a browser

http://127.0.0.1:8000/items/?skip=0&limit=10

The above two URLs have the same output.

Also, for example, the following URL:

http://127.0.0.1:8000/items/?skip=20

If you access to, the parameters of the function will be:

--skip = 20 set in the URL --Default value limit = 10

Optional parameters It is also possible to declare ** Query parameters ** that can be used as options by setting the default value to None. As an example, check the code below.

main.py


from typing import Optional     #Import Optional from typing package

from fastapi import FastAPI

app = FastAPI()


@app.get("/items/{item_id}")
async def read_item(item_id: str, q: Optional[str] = None):     #Query parameter"q"Is declared as an optional parameter
    if q:
        return {"item_id": item_id, "q": q}
    return {"item_id": item_id}

In this case, the function parameter q is treated as an option and is treated as None by default.

Notice that the Fast API understands that ʻitem_id is a ** Path parameter ** and q` is a ** Query parameter ** instead of a ** Path parameter **. ..

Also, the Fast API recognizes that q is an optional parameter just by declaring = None. ʻOptional is not used by the Fast API itself. The purpose of making it explicit as ʻOptional [str] is that the editor support can detect the error in advance.

Query parameter type conversion

You can declare the bool type as a ** Query parameter **, in which case the Fast API will convert the parameter to a suitable form. As an example, check the code below.

main.py


from typing import Optional

from fastapi import FastAPI

app = FastAPI()


@app.get("/items/{item_id}")
#Bool type is specified in the query parameter of the argument
async def read_item(item_id: str, q: Optional[str] = None, short: bool = False):
    item = {"item_id": item_id}
    if q:
        item.update({"q": q})
    if not short:
        item.update(
            {"description": "This is an amazing item that has a long description"}
        )
    return item

For such code, you can access it as follows:

For these URLs, all parameters short are treated as True with a bool value. (The same is true if the first letter is changed from lowercase to uppercase) If the value is other than the above, it will be False. In this way, when bool type is specified in ** Query parameter **, conversion is performed by Fast API.

Multiple path and query parameters

In FastAPI, it works fine even if you declare multiple ** Path parameters ** and ** Query parameters ** at the same time as function arguments. You also don't have to declare them in any particular order. This is because FastAPI recognizes parameters by name.

For example, if you have code like this:

main


from typing import Optional

from fastapi import FastAPI

app = FastAPI()


@app.get("/users/{user_id}/items/{item_id}")    # <- {user_id}When{item_id}をPathパラメータWhenして指定
async def read_user_item(
    user_id: int, item_id: str, q: Optional[str] = None, short: bool = False    # <-Not a Path parameter"q"When"short"はQueryパラメータWhenして扱う
):
    item = {"item_id": item_id, "owner_id": user_id}
    if q:
        item.update({"q": q})
    if not short:
        item.update(
            {"description": "This is an amazing item that has a long description"}
        )
    return item

In this case, there is no problem even if you change the order of the function arguments. FastAPI recognizes each parameter based on the name of the parameter.

Required query parameters

If you declare a default value with a parameter other than Path (although we're only learning Query parameters at this time), that parameter is no longer a mandatory parameter. This is because if the parameter is omitted, the default value is specified.

You can also declare a parameter as an optional parameter without adding a specific value by setting the default value to None.

Then, what to do when you want to set ** Query parameter ** as an indispensable parameter that cannot be omitted, you can do it by not declaring the default value.

main


from fastapi import FastAPI

app = FastAPI()


@app.get("/items/{item_id}")
async def read_user_item(item_id: str, needy: str):     # <-Declaring the parameter needley without specifying a default value
    item = {"item_id": item_id, "needy": needy}
    return item

The needy parameter above is declared as a required str type ** Query parameter **. If you have a URL like this:

http://127.0.0.1:8000/items/foo-item

If you open in a browser, you will see the following error because the required parameter needy has not been added.

{
    "detail": [
        {
            "loc": [
                "query",
                "needy"
            ],
            "msg": "field required",
            "type": "value_error.missing"
        }
    ]
}

needy is a required parameter, so you need to specify it in the URL as below:

http://127.0.0.1:8000/items/foo-item?needy=sooooneedy

This URL should look like this:

{
    "item_id": "foo-item",
    "needy": "sooooneedy"
}

Of course, it is possible to define required parameters, parameters with default values, and optional parameters at the same time.

main


from typing import Optional

from fastapi import FastAPI

app = FastAPI()


@app.get("/items/{item_id}")
async def read_user_item(
    item_id: str, needy: str, skip: int = 0, limit: Optional[int] = None    # <-
):
    item = {"item_id": item_id, "needy": needy, "skip": skip, "limit": limit}
    return item

In the code above, three query parameters are declared.

--needy: Required parameter of type str (without default value) --skip: ʻinttype parameter with default value0 --limit: ʻint type optional parameter

You can use ʻEnum` in ** Query parameter ** as well as ** Path parameter **. See Path Parameters for details.

At the end

This time I learned how to use the ** Query parameter **. All the code used in this article is taken from the Official Documentation (https://fastapi.tiangolo.com/tutorial/query-params/), I have confirmed that it works in my local environment.

Next time, we will study ** Request Body **.

Recommended Posts

FastAPI Tutorial Memo Part 3 Query Parameters
FastAPI Tutorial Memo Part 2 Path Parameters
FastAPI Tutorial Memo Part 1
django tutorial memo
[For memo] Linux Part 2
List memo writing part 2
Python basic memo --Part 2
Python OpenCV tutorial memo
Python basic memo --Part 1
Android HCE Survey Memo (Part 2)
pyramid tutorial memo (bank account)
Power Query Technique Collection Part 1
Get query parameters for Flask GET
Linux standard textbook memo 1 part 2
Python Basic Grammar Memo (Part 1)
Linux standard textbook memo part 6