Fastapi: [QUESTION] How can I create a custom description and validation of a query?

Created on 20 Nov 2019  路  2Comments  路  Source: tiangolo/fastapi

Description

Suppose that a given route returns tabular data, and the user can specify the order of the retrieval. I wish to declare that order as a GET parameter of the following form:

sort=+amount to sort by column amount ascending; sort=-amount to sort by column amount descending. I would like this to be described in the swagger (as free text and with an example).

Currently I have:

class Sort(str):
    @classmethod
    def __get_validators__(cls):
        yield cls.validate

    @classmethod
    def validate(cls, v):
        if not isinstance(v, str):
            raise ValueError(f'Sort must be a string.')
        if len(v) == 0:
            raise ValueError(f'Sort must be non-empty.')
        if v[0] not in {'+', '-'}:
            raise ValueError(f'Sort\'s first character must be either "+" or "-"')
        return v

def data(sort: Sort = None, search: str = None, page: int = 1):
    if sort is not None:
        order, column = sort[0], sort[1:]
        if column not in ['amount', 'foo']:
            raise ...[what?]
        ...
  1. What should I add in [What?]
  2. how do I change the description of Sort?
question

All 2 comments

Hey @jorgecarleitao, I think you just need to read this docs section carefully :) https://fastapi.tiangolo.com/tutorial/query-params-str-validations/

@jorgecarleitao it seems you just need an int that can be positive or negative, right?

As @shifr points out, check those docs, and these: https://fastapi.tiangolo.com/tutorial/path-params-numeric-validations/

from fastapi import FastAPI

app = FastAPI()


@app.get("/")
def data(sort: int = None, search: str = None, page: int = 1):
    return {"some": "data"}
Was this page helpful?
0 / 5 - 0 ratings

Related issues

DrPyser picture DrPyser  路  3Comments

scheung38 picture scheung38  路  3Comments

updatatoday picture updatatoday  路  3Comments

danielgtaylor picture danielgtaylor  路  3Comments

zero0nee picture zero0nee  路  3Comments