Python fastapi.Query() Examples

The following are 30 code examples of fastapi.Query(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module fastapi , or try the search function .
Example #1
Source File: pagination.py    From fastapi_contrib with MIT License 8 votes vote down vote up
def __new__(mcs, name, bases, namespace, *args, **kwargs):
        cls = super(PaginationMeta, mcs).__new__(mcs, name, bases, namespace)
        _cls__init__ = cls.__init__

        def __init__(
            self,
            request: Request,
            offset: int = Query(
                default=cls.default_offset, ge=0, le=cls.max_offset
            ),
            limit: int = Query(
                default=cls.default_limit, ge=1, le=cls.max_limit
            ),
        ):
            _cls__init__(self, request, offset, limit)

        setattr(cls, "__init__", __init__)
        return cls 
Example #2
Source File: directions.py    From idunn with Apache License 2.0 7 votes vote down vote up
def get_directions_with_coordinates(
    # URL values
    f_lon: float,
    f_lat: float,
    t_lon: float,
    t_lat: float,
    # Query parameters
    type: str,
    language: str = "en",
    # Request
    request: Request = Depends(directions_request),
):
    from_place = Latlon(f_lat, f_lon)
    to_place = Latlon(t_lat, t_lon)
    if not type:
        raise HTTPException(status_code=400, detail='"type" query param is required')
    return directions_client.get_directions(
        from_place, to_place, type, language, params=request.query_params
    ) 
Example #3
Source File: pagination.py    From bitcart with MIT License 7 votes vote down vote up
def __init__(
        self,
        request: Request,
        offset: int = Query(default=default_offset, ge=0, le=max_offset),
        limit: int = Query(default=default_limit, ge=-1, le=max_limit),
        query: str = Query(default=""),
        multiple: bool = Query(default=False),
        sort: str = Query(default=""),
        desc: bool = Query(default=True),
    ):
        self.request = request
        self.offset = offset
        self.limit = limit
        self.query = query
        self.multiple = multiple
        if self.multiple:
            self.query = self.query.replace(",", "|")
        self.sort = sort
        self.desc = desc
        self.desc_s = "desc" if desc else ""
        self.model: Optional["ModelType"] = None 
Example #4
Source File: directions.py    From idunn with Apache License 2.0 7 votes vote down vote up
def get_directions(
    # Query parameters
    origin: str = Query(..., description="Origin place id"),
    destination: str = Query(..., description="Destination place id"),
    type: str = Query(..., description="Transport mode"),
    language: str = Query("en", description="User language"),
    # Request
    request: Request = Depends(directions_request),
):
    rate_limiter.check_limit_per_client(request)
    try:
        from_place = place_from_id(origin)
        to_place = place_from_id(destination)
    except InvalidPlaceId as exc:
        raise HTTPException(status_code=404, detail=exc.message)

    return directions_client.get_directions(
        from_place, to_place, type, language, params=request.query_params
    ) 
Example #5
Source File: test_exception_handlers.py    From fastapi_contrib with MIT License 7 votes vote down vote up
def pydantic_exception_invalid_query(q: int = Query(...)):
    return {"q": q}


# def test_exception_handler_invalid_query():
#     with TestClient(app) as client:
#         response = client.get(
#             "/pydantic/exception/invalidquery/", params={"q": "$"}
#         )
#         assert response.status_code == 400
#         response = response.json()
#         assert response["error_codes"] == [400]
#         assert response["message"] == "Validation error."
#         assert response["fields"] == [
#             {
#                 "name": "q",
#                 "message": "Value is not a valid integer.",
#                 "error_code": 400,
#             }
#         ] 
Example #6
Source File: tutorial010.py    From fastapi with MIT License 6 votes vote down vote up
def read_items(
    q: Optional[str] = Query(
        None,
        alias="item-query",
        title="Query string",
        description="Query string for the items to search in the database that have a good match",
        min_length=3,
        max_length=50,
        regex="^fixedquery$",
        deprecated=True,
    )
):
    results = {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]}
    if q:
        results.update({"q": q})
    return results 
Example #7
Source File: test_multi_query_errors.py    From fastapi with MIT License 6 votes vote down vote up
def read_items(q: List[int] = Query(None)):
    return {"q": q} 
Example #8
Source File: test_invalid_sequence_param.py    From fastapi with MIT License 6 votes vote down vote up
def test_invalid_dict():
    with pytest.raises(AssertionError):
        app = FastAPI()

        class Item(BaseModel):
            title: str

        @app.get("/items/")
        def read_items(q: Dict[str, Item] = Query(None)):
            pass  # pragma: no cover 
Example #9
Source File: query_params.py    From optimade-python-tools with MIT License 6 votes vote down vote up
def __init__(
        self,
        *,
        response_format: str = Query(
            "json",
            description="The output format requested (see section Response Format).\nDefaults to the format string 'json', which specifies the standard output format described in this specification.\nExample: `http://example.com/v1/structures?response_format=xml`",
        ),
        email_address: EmailStr = Query(
            "",
            description="An email address of the user making the request.\nThe email SHOULD be that of a person and not an automatic system.\nExample: `http://example.com/v1/structures?email_address=user@example.com`",
        ),
        response_fields: str = Query(
            "",
            description="A comma-delimited set of fields to be provided in the output.\nIf provided, these fields MUST be returned along with the REQUIRED fields.\nOther OPTIONAL fields MUST NOT be returned when this parameter is present.\nExample: `http://example.com/v1/structures?response_fields=last_modified,nsites`",
            regex=r"([a-z_][a-z_0-9]*(,[a-z_][a-z_0-9]*)*)?",
        ),
        include: str = Query(
            "references",
            description='A server MAY implement the JSON API concept of returning [compound documents](https://jsonapi.org/format/1.0/#document-compound-documents) by utilizing the `include` query parameter as specified by [JSON API 1.0](https://jsonapi.org/format/1.0/#fetching-includes).\n\nAll related resource objects MUST be returned as part of an array value for the top-level `included` field, see the section JSON Response Schema: Common Fields.\n\nThe value of `include` MUST be a comma-separated list of "relationship paths", as defined in the [JSON API](https://jsonapi.org/format/1.0/#fetching-includes).\nIf relationship paths are not supported, or a server is unable to identify a relationship path a `400 Bad Request` response MUST be made.\n\nThe **default value** for `include` is `references`.\nThis means `references` entries MUST always be included under the top-level field `included` as default, since a server assumes if `include` is not specified by a client in the request, it is still specified as `include=references`.\nNote, if a client explicitly specifies `include` and leaves out `references`, `references` resource objects MUST NOT be included under the top-level field `included`, as per the definition of `included`, see section JSON Response Schema: Common Fields.\n\n> **Note**: A query with the parameter `include` set to the empty string means no related resource objects are to be returned under the top-level field `included`.',
        ),
    ):
        self.response_format = response_format
        self.email_address = email_address
        self.response_fields = response_fields
        self.include = include 
Example #10
Source File: vps.py    From LuWu with Apache License 2.0 5 votes vote down vote up
def get_vps_specs(db: Session = Depends(get_db), *, isp_id: int = Query(0, alias='ispId')):
    rp = RedisPool()
    vps_raw_spec_data = rp.get_vps_spec_data(db_session=db, isp_id=isp_id)
    vps_spec_data = VpsSpecSchema(**vps_raw_spec_data)

    return dict(result=vps_spec_data) 
Example #11
Source File: pagination.py    From fastapi_contrib with MIT License 5 votes vote down vote up
def __init__(
        self,
        request: Request,
        offset: int = Query(default=default_offset, ge=0, le=max_offset),
        limit: int = Query(default=default_limit, ge=1, le=max_limit),
    ):
        self.request = request
        self.offset = offset
        self.limit = limit
        self.model = None
        self.count = None
        self.list = [] 
Example #12
Source File: vps.py    From LuWu with Apache License 2.0 5 votes vote down vote up
def get_vps_ssh_keys(db: Session = Depends(get_db), *, isp_id: int = Query(..., alias='ispId')):
    ssh_key_list = []
    vps_isp_obj = crud_isp.get(db_session=db, id=isp_id)
    if vps_isp_obj:
        ssh_key_list = vps_isp_obj.isp_instance.get_ssh_key_list(isp_id)

    return dict(result=ssh_key_list) 
Example #13
Source File: query.py    From LuWu with Apache License 2.0 5 votes vote down vote up
def __init__(
        self,
        page: int = Query(1),
        per_page: int = Query(config.PAGINATION_PER_PAGE, alias='perPage'),
        count: bool = Query(True),
        query_all: bool = Query(False, alias='queryAll'),
    ):
        self.page = page
        self.per_page = per_page
        self.count = count
        self.query_all = query_all 
Example #14
Source File: articles.py    From fastapi-realworld-example-app with MIT License 5 votes vote down vote up
def get_articles_filters(
    tag: Optional[str] = None,
    author: Optional[str] = None,
    favorited: Optional[str] = None,
    limit: int = Query(DEFAULT_ARTICLES_LIMIT, ge=1),
    offset: int = Query(DEFAULT_ARTICLES_OFFSET, ge=0),
) -> ArticlesFilters:
    return ArticlesFilters(
        tag=tag, author=author, favorited=favorited, limit=limit, offset=offset,
    ) 
Example #15
Source File: articles_common.py    From fastapi-realworld-example-app with MIT License 5 votes vote down vote up
def get_articles_for_user_feed(
    limit: int = Query(DEFAULT_ARTICLES_LIMIT, ge=1),
    offset: int = Query(DEFAULT_ARTICLES_OFFSET, ge=0),
    user: User = Depends(get_current_user_authorizer()),
    articles_repo: ArticlesRepository = Depends(get_repository(ArticlesRepository)),
) -> ListOfArticlesInResponse:
    articles = await articles_repo.get_articles_for_user_feed(
        user=user, limit=limit, offset=offset,
    )
    articles_for_response = [
        ArticleForResponse(**article.dict()) for article in articles
    ]
    return ListOfArticlesInResponse(
        articles=articles_for_response, articles_count=len(articles),
    ) 
Example #16
Source File: places_list.py    From idunn with Apache License 2.0 5 votes vote down vote up
def get_events_bbox(
    bbox: str,
    category: Optional[str] = Query(None),
    size: int = Query(None),
    lang: Optional[str] = Query(None),
    verbosity: Optional[str] = Query(None),
):
    if not kuzzle_client.enabled:
        raise HTTPException(status_code=501, detail="Kuzzle client is not available")

    try:
        params = EventQueryParam(
            **{
                "category": category,
                "bbox": bbox,
                "size": size,
                "lang": lang,
                "verbosity": verbosity,
            }
        )
    except ValidationError as e:
        logger.info(f"Validation Error: {e.json()}")
        raise HTTPException(status_code=400, detail=e.errors())

    current_outing_lang = params.category

    if params.category:
        current_outing_lang = params.category.get("fr")

    bbox_places = kuzzle_client.fetch_event_places(
        bbox=params.bbox, collection="events", category=current_outing_lang, size=params.size
    )

    events_list = [Event(p["_source"]) for p in bbox_places]

    return {"events": [p.load_place(params.lang, params.verbosity) for p in events_list]} 
Example #17
Source File: tutorial003.py    From fastapi with MIT License 5 votes vote down vote up
def read_items(q: Optional[str] = Query(None, min_length=3, max_length=50)):
    results = {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]}
    if q:
        results.update({"q": q})
    return results 
Example #18
Source File: tutorial011.py    From fastapi with MIT License 5 votes vote down vote up
def read_items(q: Optional[List[str]] = Query(None)):
    query_items = {"q": q}
    return query_items 
Example #19
Source File: tutorial004.py    From fastapi with MIT License 5 votes vote down vote up
def read_items(
    q: Optional[str] = Query(None, min_length=3, max_length=50, regex="^fixedquery$")
):
    results = {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]}
    if q:
        results.update({"q": q})
    return results 
Example #20
Source File: app.py    From mquery with GNU Affero General Public License v3.0 5 votes vote down vote up
def matches(
    hash: str, offset: int = Query(...), limit: int = Query(...)
) -> MatchesSchema:
    """
    Returns a list of matched files, along with metadata tags and other
    useful information. Results from this query can be used to download files
    using the `/download` endpoint.
    """
    return db.get_job_matches(JobId(hash), offset, limit) 
Example #21
Source File: tutorial006.py    From fastapi with MIT License 5 votes vote down vote up
def read_items(q: str = Query(..., min_length=3)):
    results = {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]}
    if q:
        results.update({"q": q})
    return results 
Example #22
Source File: tutorial009.py    From fastapi with MIT License 5 votes vote down vote up
def read_items(q: Optional[str] = Query(None, alias="item-query")):
    results = {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]}
    if q:
        results.update({"q": q})
    return results 
Example #23
Source File: tutorial002.py    From fastapi with MIT License 5 votes vote down vote up
def read_items(q: Optional[str] = Query(None, max_length=50)):
    results = {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]}
    if q:
        results.update({"q": q})
    return results 
Example #24
Source File: tutorial008.py    From fastapi with MIT License 5 votes vote down vote up
def read_items(
    q: Optional[str] = Query(
        None,
        title="Query string",
        description="Query string for the items to search in the database that have a good match",
        min_length=3,
    )
):
    results = {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]}
    if q:
        results.update({"q": q})
    return results 
Example #25
Source File: tutorial013.py    From fastapi with MIT License 5 votes vote down vote up
def read_items(q: list = Query([])):
    query_items = {"q": q}
    return query_items 
Example #26
Source File: tutorial012.py    From fastapi with MIT License 5 votes vote down vote up
def read_items(q: List[str] = Query(["foo", "bar"])):
    query_items = {"q": q}
    return query_items 
Example #27
Source File: tutorial002.py    From fastapi with MIT License 5 votes vote down vote up
def get_cookie_or_token(
    websocket: WebSocket,
    session: Optional[str] = Cookie(None),
    token: Optional[str] = Query(None),
):
    if session is None and token is None:
        await websocket.close(code=status.WS_1008_POLICY_VIOLATION)
    return session or token 
Example #28
Source File: tutorial001.py    From fastapi with MIT License 5 votes vote down vote up
def read_items(
    item_id: int = Path(..., title="The ID of the item to get"),
    q: Optional[str] = Query(None, alias="item-query"),
):
    results = {"item_id": item_id}
    if q:
        results.update({"q": q})
    return results 
Example #29
Source File: tutorial006.py    From fastapi with MIT License 5 votes vote down vote up
def read_items(
    *,
    item_id: int = Path(..., title="The ID of the item to get", ge=0, le=1000),
    q: str,
    size: float = Query(..., gt=0, lt=10.5)
):
    results = {"item_id": item_id}
    if q:
        results.update({"q": q})
    return results 
Example #30
Source File: main.py    From fastapi with MIT License 5 votes vote down vote up
def get_query_param_required_type(query: int = Query(...)):
    return f"foo bar {query}"