|
| 1 | + |
| 2 | +[](https://codecov.io/gh/JGoutin/fastapi_paginator) |
| 3 | +[](https://pypi.org/project/fastapi_paginator) |
| 4 | + |
| 5 | +# FastAPI Paginator |
| 6 | + |
| 7 | +Easy to use paginator for [FastAPI](https://fastapi.tiangolo.com/) |
| 8 | + |
| 9 | +Currently, supports only [encode/databases](https://github.com/encode/databases) as |
| 10 | +database library and tested with SQlite and PostgreSQL. |
| 11 | + |
| 12 | +## Features |
| 13 | + |
| 14 | +* Simple FastAPI integration. |
| 15 | +* Navigation with page numbers (With total page count returned on first page). |
| 16 | +* Navigation from a specific row (since). |
| 17 | +* Ordering result (On multiple columns). |
| 18 | +* Filtering result using various SQL functions. |
| 19 | + |
| 20 | +## Installation |
| 21 | + |
| 22 | +FastAPI Paginator is available on PyPI, so it can be installed like any other Python |
| 23 | +package. |
| 24 | + |
| 25 | +Example with Pip: |
| 26 | +```bash |
| 27 | +pip install fastapi_paginator |
| 28 | +``` |
| 29 | + |
| 30 | +## Usage |
| 31 | + |
| 32 | +### Routes creations in FastAPI |
| 33 | + |
| 34 | +To use it, you only need to create a `fastapi_paginator.Paginator` instance linked to |
| 35 | +the database and routes |
| 36 | +using `fastapi_paginator.PageParameters` and `fastapi_paginator.Page`. |
| 37 | + |
| 38 | +```python |
| 39 | +import databases |
| 40 | +import fastapi |
| 41 | +import pydantic |
| 42 | +import sqlalchemy |
| 43 | +import fastapi_paginator |
| 44 | + |
| 45 | +# Already existing database, FastAPI application, "item" table, and "item" model |
| 46 | +database = databases.Database(f"sqlite:///local.db}") |
| 47 | +app = fastapi.FastAPI() |
| 48 | + |
| 49 | +table = sqlalchemy.Table( |
| 50 | + "table", |
| 51 | + sqlalchemy.MetaData(), |
| 52 | + Column("id", sqlalchemy.Integer, primary_key=True), |
| 53 | + Column("name", sqlalchemy.String, nullable=False), |
| 54 | +) |
| 55 | + |
| 56 | +class Item(pydantic.BaseModel): |
| 57 | + """Item in database.""" |
| 58 | + |
| 59 | + class Config: |
| 60 | + """Config.""" |
| 61 | + |
| 62 | + orm_mode = True # Required |
| 63 | + |
| 64 | + id: int |
| 65 | + name: str |
| 66 | + |
| 67 | + |
| 68 | +# Create a paginator for the database (Required only once per database) |
| 69 | +paginator = fastapi_paginator.Paginator(database) |
| 70 | + |
| 71 | +# Create a paginated route |
| 72 | +@app.get("/list") |
| 73 | +async def list_data( |
| 74 | + page_parameters: fastapi_paginator.PageParameters = Depends(), |
| 75 | +) -> fastapi_paginator.Page[Item]: |
| 76 | + """List data with pagination.""" |
| 77 | + return await paginator(table.select(), Item, page_parameters) |
| 78 | +``` |
| 79 | + |
| 80 | +### Paginated routes usage from clients |
| 81 | + |
| 82 | + |
| 83 | +#### Request |
| 84 | +Paginator parameters are passed as query parameters, for instance: |
| 85 | + |
| 86 | +```http request |
| 87 | +GET /list?order_by=id&page=2 |
| 88 | +``` |
| 89 | + |
| 90 | +##### Query parameters |
| 91 | + |
| 92 | +###### page |
| 93 | +The page to return. |
| 94 | + |
| 95 | +When page is not specified or equal to `1`, the request returns `total_page` that is |
| 96 | +the maximum number of pages. |
| 97 | + |
| 98 | +*Cannot be used with `since`.* |
| 99 | + |
| 100 | +###### since |
| 101 | + |
| 102 | +The item from where starting to return the result. |
| 103 | + |
| 104 | +When navigating between successive pages, the `next_since` returned value should be used |
| 105 | +as `since` for the subsequent requests. |
| 106 | + |
| 107 | +*Cannot be used with `page`*. |
| 108 | + |
| 109 | +*Cannot be used with `order_by` if not ordering on the field used by `since`*. |
| 110 | + |
| 111 | +###### order_by |
| 112 | +Sort the resulting items by the specified field name. |
| 113 | + |
| 114 | +Order is descending if `-` is added before the field name, else order is ascending. |
| 115 | + |
| 116 | +This query parameter can be specified multiple time to sort by multiple columns. |
| 117 | + |
| 118 | +**Example:** |
| 119 | +"Ordering descending by the `created_at` column: `order_by=-created_at` |
| 120 | + |
| 121 | +###### filter_by |
| 122 | + |
| 123 | +Filter the resulting items. |
| 124 | + |
| 125 | +The query must be in the form `field_name operator argument`, with: |
| 126 | + * `field_name`: the name on the field on where apply the filter. |
| 127 | + * `operator`: one operator from the list bellow. |
| 128 | + * `argument`: is the operator argument, it can be one or more value separated by `,` |
| 129 | + (Depending on the operator), valid values must be a primitive JSON type like |
| 130 | + numbers, double-quoted strings, `true`, `false` and `null`. |
| 131 | + |
| 132 | +This query parameter can be specified multiple time to filter on more criteria |
| 133 | +(Using AND logical conjunction). |
| 134 | + |
| 135 | +Available operators: |
| 136 | + * `=`: Equal to a single value (Also supports `null`, `true` and `false`) |
| 137 | + * `<`: Lower than a single value. |
| 138 | + * `<=`: Lower or equal than a single value. |
| 139 | + * `>`: Greater than a single value. |
| 140 | + * `>=`: Greater or equal than a single value. |
| 141 | + * `between`: Between a pair of values (`value_1` <= `field_value` <= `value_2`). |
| 142 | + * `in`: Present in a list of one or more values. |
| 143 | + * `like`: Like a single value (`%` can be used as wildcard for zero to multiple |
| 144 | + characters, `_` as wildcard for a single character, `/` can be used as escape |
| 145 | + character for `%` and `_`). |
| 146 | + * `ilike`: Same as `like`, but case insensitive. |
| 147 | + * `startswith`: String representation starts with a single value. |
| 148 | + * `endswith`: String representation ends with a single value. |
| 149 | + * `contains`: String representation contains a single value. |
| 150 | + |
| 151 | +Any operator can be negated by adding `!` in front of it. |
| 152 | + |
| 153 | +*Warning*: Depending on your HTTP client, the query parameter value may require to be |
| 154 | +URL encoded. |
| 155 | + |
| 156 | +**Example:** |
| 157 | +Returning only data with a `name` field that does not start with |
| 158 | +`Product`: `filter_by=name%20%21like%20%22Product%25%22` |
| 159 | +(With URL encoded value of: `name !like "Product%"`') |
| 160 | + |
| 161 | +##### Response |
| 162 | + |
| 163 | +The response is a JSON dictionnary with the following fields: |
| 164 | +* `items`: The list returned items. |
| 165 | +* `next_since`: Next value to use with `since` query parameter. |
| 166 | +* `next_page`: Next value to use with `page` query parameter. |
| 167 | +* `total_pages`: Total pages, only computed and returned when on page 1 |
| 168 | + |
| 169 | +### Using alternates JSON libraries |
| 170 | + |
| 171 | +It is possible to override the `json.loads` function used in all paginator as follows |
| 172 | +(Example with [orjson](https://github.com/ijl/orjson)): |
| 173 | + |
| 174 | +```python |
| 175 | +import orjson |
| 176 | +import fastapi_paginator |
| 177 | + |
| 178 | + |
| 179 | +fastapi_paginator.Paginator.json_loads = orjson.loads |
| 180 | +``` |
0 commit comments