| 1 |
.. _rest-api: |
| 2 |
|
| 3 |
REST API |
| 4 |
======== |
| 5 |
|
| 6 |
flask-peewee comes with some tools for exposing your project's models via a |
| 7 |
REST API. There are several components to the ``rest`` module, but the basic |
| 8 |
setup is to create an instance of :py:class:`RestAPI` and then register your |
| 9 |
project's models with subclasses of :py:class:`RestResource`. |
| 10 |
|
| 11 |
Each :py:class:`RestResource` you expose via the API will support, by default, |
| 12 |
the following: |
| 13 |
|
| 14 |
* ``/api/<model name>/`` -- GET and POST requests |
| 15 |
* ``/api/<model name>/<primary key>/`` -- GET, PUT and DELETE requests |
| 16 |
|
| 17 |
Also, you can filter results by columns on the model using django-style syntax, |
| 18 |
for example: |
| 19 |
|
| 20 |
* ``/api/blog/?name=Some%20Blog`` |
| 21 |
* ``/api/blog/?author__username=some_blogger`` |
| 22 |
|
| 23 |
Full operations: |
| 24 |
|
| 25 |
* ``__eq``: equals |
| 26 |
* ``__lt``: less-than |
| 27 |
* ``__lte``: less-than or equal to |
| 28 |
* ``__gt``: greater-than |
| 29 |
* ``__gte``: greater-than or equal to |
| 30 |
* ``__ne``: not equal to |
| 31 |
* ``__in``: in set |
| 32 |
* ``__is``: is, ``?field__is=None`` or ``?-field__is=None`` for NOT NULL |
| 33 |
* ``__is_not``: is not , ``?field__is_not=None`` |
| 34 |
* ``__like``: wild-card matching, case-sensitive |
| 35 |
* ``__ilike``: wild-card matching, case-insensitive |
| 36 |
* ``__regexp``: regular-expression matching (database-specific) |
| 37 |
|
| 38 |
To negate an operation, prefix it with the ``-`` character, e.g. the following |
| 39 |
are equivalent: |
| 40 |
|
| 41 |
* ``/api/user/?admin=true`` |
| 42 |
* ``/api/user/?admin__eq=true`` |
| 43 |
* ``/api/user/?-admin=false`` |
| 44 |
* ``/api/user/?admin__ne=false`` |
| 45 |
|
| 46 |
Special Python constants are supported when used as querystring parameters: |
| 47 |
|
| 48 |
* ``?value=none`` translates the value to ``None`` |
| 49 |
* ``?value=true`` translates the value to ``True`` |
| 50 |
* ``?value=false`` translates the value to ``False`` |
| 51 |
|
| 52 |
Getting started with the API |
| 53 |
---------------------------- |
| 54 |
|
| 55 |
In this documentation we'll start with a very simple API and build it out. The |
| 56 |
complete version of this API is included in the `example app |
| 57 |
<https://github.com/coleifer/flask-peewee/tree/master/example>`_, so feel free |
| 58 |
to refer there. |
| 59 |
|
| 60 |
The project will be a simple 'twitter-like' app where users can post short messages |
| 61 |
and "follow" other users. |
| 62 |
|
| 63 |
.. note:: If you're using apache with mod_wsgi and would like to use any of |
| 64 |
the auth backends that use basic auth, you will need to add the following |
| 65 |
directive: ``WSGIPassAuthorization On`` |
| 66 |
|
| 67 |
|
| 68 |
Project models |
| 69 |
^^^^^^^^^^^^^^ |
| 70 |
|
| 71 |
There are three main models - ``User``, ``Relationship`` and ``Message`` - which |
| 72 |
we will expose via the API. Here is a truncated version of what they look like: |
| 73 |
|
| 74 |
.. code-block:: python |
| 75 |
|
| 76 |
from flask_peewee.auth import BaseUser |
| 77 |
|
| 78 |
class User(db.Model, BaseUser): |
| 79 |
username = CharField() |
| 80 |
password = CharField() |
| 81 |
email = CharField() |
| 82 |
join_date = DateTimeField(default=datetime.datetime.now) |
| 83 |
active = BooleanField(default=True) |
| 84 |
admin = BooleanField(default=False) |
| 85 |
|
| 86 |
class Relationship(db.Model): |
| 87 |
from_user = ForeignKeyField(User, backref='relationships') |
| 88 |
to_user = ForeignKeyField(User, backref='related_to') |
| 89 |
|
| 90 |
class Message(db.Model): |
| 91 |
user = ForeignKeyField(User) |
| 92 |
content = TextField() |
| 93 |
pub_date = DateTimeField(default=datetime.datetime.now) |
| 94 |
|
| 95 |
|
| 96 |
Creating a RestAPI |
| 97 |
------------------ |
| 98 |
|
| 99 |
The :py:class:`RestAPI` acts as a container for the various :py:class:`RestResource` |
| 100 |
objects we will expose. By default it binds all resources to ``/api/<model-name>/``. |
| 101 |
|
| 102 |
Here we'll create a simple api and register our models: |
| 103 |
|
| 104 |
.. code-block:: python |
| 105 |
|
| 106 |
from flask_peewee.rest import RestAPI |
| 107 |
|
| 108 |
from app import app # our project's Flask app |
| 109 |
|
| 110 |
# instantiate our api wrapper |
| 111 |
api = RestAPI(app) |
| 112 |
|
| 113 |
# register our models so they are exposed via /api/<model>/ |
| 114 |
api.register(User) |
| 115 |
api.register(Relationship) |
| 116 |
api.register(Message) |
| 117 |
|
| 118 |
# configure the urls |
| 119 |
api.setup() |
| 120 |
|
| 121 |
|
| 122 |
Now if we hit our project at ``/api/message/`` we should get something like the following: |
| 123 |
|
| 124 |
.. code-block:: javascript |
| 125 |
|
| 126 |
{ |
| 127 |
"meta": { |
| 128 |
"model": "message", |
| 129 |
"next": "", |
| 130 |
"page_count": 1, |
| 131 |
"page": 1, |
| 132 |
"previous": "" |
| 133 |
}, |
| 134 |
"objects": [ |
| 135 |
{ |
| 136 |
"content": "flask and peewee, together at last!", |
| 137 |
"pub_date": "2026-09-16T18:36:15", |
| 138 |
"user": 1, |
| 139 |
"id": 1 |
| 140 |
}, |
| 141 |
{ |
| 142 |
"content": "Hey, I'm just some user", |
| 143 |
"pub_date": "2026-09-16T18:46:59", |
| 144 |
"user": 2, |
| 145 |
"id": 2 |
| 146 |
} |
| 147 |
] |
| 148 |
} |
| 149 |
|
| 150 |
Say we're interested in the first message, we can hit ``/api/message/1/`` to view |
| 151 |
just the details on that object: |
| 152 |
|
| 153 |
.. code-block:: javascript |
| 154 |
|
| 155 |
{ |
| 156 |
"content": "flask and peewee, together at last!", |
| 157 |
"pub_date": "2026-09-16T18:36:15", |
| 158 |
"user": 1, |
| 159 |
"id": 1 |
| 160 |
} |
| 161 |
|
| 162 |
|
| 163 |
Customizing what is returned |
| 164 |
---------------------------- |
| 165 |
|
| 166 |
If you access the ``User`` API endpoint, we quickly notice a problem: |
| 167 |
|
| 168 |
.. code-block:: console |
| 169 |
|
| 170 |
$ curl http://127.0.0.1:5000/api/user/ |
| 171 |
|
| 172 |
{ |
| 173 |
"meta": { |
| 174 |
"model": "user", |
| 175 |
"next": "", |
| 176 |
"page": 1, |
| 177 |
"page_count": 1, |
| 178 |
"previous": "" |
| 179 |
}, |
| 180 |
"objects": [ |
| 181 |
{ |
| 182 |
"username": "admin", |
| 183 |
"admin": true, |
| 184 |
"email": "", |
| 185 |
"join_date": "2026-09-16T18:34:49", |
| 186 |
"active": true, |
| 187 |
"password": "d033e22ae348aeb5660fc2140aec35850c4da997", |
| 188 |
"id": 1 |
| 189 |
}, |
| 190 |
{ |
| 191 |
"username": "coleifer", |
| 192 |
"admin": false, |
| 193 |
"email": "[email protected]", |
| 194 |
"join_date": "2026-09-16T18:35:56", |
| 195 |
"active": true, |
| 196 |
"password": "a94a8fe5ccb19ba61c4c0873d391e987982fbbd3", |
| 197 |
"id": 2 |
| 198 |
} |
| 199 |
] |
| 200 |
} |
| 201 |
|
| 202 |
Passwords and email addresses are being exposed. In order to exclude these fields |
| 203 |
from serialization, subclass :py:class:`RestResource`: |
| 204 |
|
| 205 |
.. code-block:: python |
| 206 |
|
| 207 |
from flask_peewee.rest import RestAPI, RestResource |
| 208 |
|
| 209 |
from app import app # our project's Flask app |
| 210 |
|
| 211 |
# instantiate our api wrapper |
| 212 |
api = RestAPI(app) |
| 213 |
|
| 214 |
# create a special resource for users that excludes email and password |
| 215 |
class UserResource(RestResource): |
| 216 |
exclude = ('password', 'email',) |
| 217 |
|
| 218 |
# register our models so they are exposed via /api/<model>/ |
| 219 |
api.register(User, UserResource) # specify the UserResource |
| 220 |
api.register(Relationship) |
| 221 |
api.register(Message) |
| 222 |
|
| 223 |
Now emails and passwords are no longer returned by the API. |
| 224 |
|
| 225 |
``exclude`` is a blacklist; its positive counterpart is ``fields``, a whitelist |
| 226 |
of the *only* fields to serialize. The resource above could instead expose just |
| 227 |
the username and id: |
| 228 |
|
| 229 |
.. code-block:: python |
| 230 |
|
| 231 |
class UserResource(RestResource): |
| 232 |
fields = ('username', 'id') |
| 233 |
|
| 234 |
Reach for whichever is more convenient -- ``fields`` when you want to expose a |
| 235 |
small, fixed set of columns, ``exclude`` when you want everything but a few. |
| 236 |
|
| 237 |
|
| 238 |
Nested resources |
| 239 |
---------------- |
| 240 |
|
| 241 |
By default a foreign key is serialized as the related row's primary key -- notice |
| 242 |
the ``"user": 1`` in the message output above. To embed the *full* related |
| 243 |
object instead, point ``include_resources`` at the resource that should render it: |
| 244 |
|
| 245 |
.. code-block:: python |
| 246 |
|
| 247 |
class UserResource(RestResource): |
| 248 |
exclude = ('password', 'email',) |
| 249 |
|
| 250 |
class MessageResource(RestResource): |
| 251 |
include_resources = {'user': UserResource} |
| 252 |
|
| 253 |
api.register(User, UserResource) |
| 254 |
api.register(Message, MessageResource) |
| 255 |
|
| 256 |
Now each message embeds its author, serialized through ``UserResource`` (so the |
| 257 |
password and email are still excluded): |
| 258 |
|
| 259 |
.. code-block:: javascript |
| 260 |
|
| 261 |
{ |
| 262 |
"content": "flask and peewee, together at last!", |
| 263 |
"pub_date": "2026-09-16T18:36:15", |
| 264 |
"user": { |
| 265 |
"username": "admin", |
| 266 |
"admin": true, |
| 267 |
"active": true, |
| 268 |
"join_date": "2026-09-16T18:34:49", |
| 269 |
"id": 1 |
| 270 |
}, |
| 271 |
"id": 1 |
| 272 |
} |
| 273 |
|
| 274 |
``include_resources`` can be nested arbitrarily deep -- an included resource may |
| 275 |
itself include resources -- and one model can be embedded through more than one |
| 276 |
foreign key. For example, a ``Relationship`` resource can expand both endpoints: |
| 277 |
|
| 278 |
.. code-block:: python |
| 279 |
|
| 280 |
class RelationshipResource(RestResource): |
| 281 |
include_resources = { |
| 282 |
'from_user': UserResource, |
| 283 |
'to_user': UserResource, |
| 284 |
} |
| 285 |
|
| 286 |
The whole nested tree is loaded in a single query -- one ``JOIN`` per included |
| 287 |
foreign key -- so embedding related objects does *not* incur the N+1 queries you |
| 288 |
would get from following each row's relations lazily. |
| 289 |
|
| 290 |
Nested writes |
| 291 |
^^^^^^^^^^^^^ |
| 292 |
|
| 293 |
Included resources also work on the way *in*: a ``POST`` or ``PUT`` whose body |
| 294 |
carries a nested object (instead of a bare id) creates or updates the related row |
| 295 |
as part of the same request. Two rules keep that safe: |
| 296 |
|
| 297 |
* A resource's ``readonly_fields`` are stripped at **every** level of the |
| 298 |
payload, so a nested object cannot smuggle in a field the resource protects |
| 299 |
(e.g. slipping ``"admin": true`` into a nested user). |
| 300 |
* Each nested write must pass the child resource's own ``check_post`` / |
| 301 |
``check_put``, exactly as a direct write to that resource would -- so nesting |
| 302 |
can never be used to sidestep a resource's authorization. |
| 303 |
|
| 304 |
The entire object graph is saved in a single transaction, so if any nested write |
| 305 |
is rejected the whole request rolls back. To disable nested writes for a |
| 306 |
resource -- silently ignoring any nested object in the payload -- set |
| 307 |
``nested_writes = False``; the foreign key can still be assigned with a bare id. |
| 308 |
|
| 309 |
|
| 310 |
Allowing users to post objects |
| 311 |
------------------------------ |
| 312 |
|
| 313 |
What if we want to create new messages via the Api? Or modify/delete existing messages? |
| 314 |
|
| 315 |
.. code-block:: console |
| 316 |
|
| 317 |
$ curl -i -d '' http://127.0.0.1:5000/api/message/ |
| 318 |
|
| 319 |
HTTP/1.1 401 UNAUTHORIZED |
| 320 |
WWW-Authenticate: Basic realm="Login Required" |
| 321 |
Content-Type: text/html; charset=utf-8 |
| 322 |
|
| 323 |
Authentication failed |
| 324 |
|
| 325 |
The authentication failed because the default authentication mechanism only |
| 326 |
allows read-only access. |
| 327 |
|
| 328 |
In order to allow users to create messages via the API, we need to use a subclass |
| 329 |
of :py:class:`Authentication` that allows ``POST`` requests. We also want to ensure |
| 330 |
that the requesting user is a member of the site. |
| 331 |
|
| 332 |
For this we will use the :py:class:`UserAuthentication` class as the default auth |
| 333 |
mechanism. |
| 334 |
|
| 335 |
.. code-block:: python |
| 336 |
|
| 337 |
from auth import auth # import the Auth object used by our project |
| 338 |
|
| 339 |
from flask_peewee.rest import RestAPI, RestResource, UserAuthentication |
| 340 |
|
| 341 |
# create an instance of UserAuthentication |
| 342 |
user_auth = UserAuthentication(auth) |
| 343 |
|
| 344 |
# instantiate our api wrapper, specifying user_auth as the default |
| 345 |
api = RestAPI(app, default_auth=user_auth) |
| 346 |
|
| 347 |
# create a special resource for users that excludes email and password |
| 348 |
class UserResource(RestResource): |
| 349 |
exclude = ('password', 'email',) |
| 350 |
|
| 351 |
# register our models so they are exposed via /api/<model>/ |
| 352 |
api.register(User, UserResource) # specify the UserResource |
| 353 |
api.register(Relationship) |
| 354 |
api.register(Message) |
| 355 |
|
| 356 |
# configure the urls |
| 357 |
api.setup() |
| 358 |
|
| 359 |
Now we should be able to POST new messages. |
| 360 |
|
| 361 |
.. code-block:: python |
| 362 |
|
| 363 |
import requests |
| 364 |
|
| 365 |
# authenticate with HTTP basic auth |
| 366 |
resp = requests.post( |
| 367 |
'http://localhost:5000/api/message/', |
| 368 |
json={'user': 1, 'content': 'hello api'}, |
| 369 |
auth=('admin', 'admin'), |
| 370 |
) |
| 371 |
response = resp.json() |
| 372 |
|
| 373 |
The response object will look something like this: |
| 374 |
|
| 375 |
.. code-block:: javascript |
| 376 |
|
| 377 |
{ |
| 378 |
'content': 'hello api', |
| 379 |
'user': 1, |
| 380 |
'pub_date': '2026-09-22T11:25:02', |
| 381 |
'id': 3 |
| 382 |
} |
| 383 |
|
| 384 |
There is a problem with this, however. Notice how the ``user`` was passed in |
| 385 |
with the POST data? This effectively will let a user post a message as another user. |
| 386 |
It also means a user can use PUT requests to modify another user's message: |
| 387 |
|
| 388 |
.. code-block:: python |
| 389 |
|
| 390 |
# continued from above -- edit another user's message (id=2) |
| 391 |
resp = requests.put( |
| 392 |
'http://127.0.0.1:5000/api/message/2/', |
| 393 |
json={'content': 'haxed you, bro'}, |
| 394 |
auth=('admin', 'admin'), |
| 395 |
) |
| 396 |
response = resp.json() |
| 397 |
|
| 398 |
The response will look like this: |
| 399 |
|
| 400 |
.. code-block:: javascript |
| 401 |
|
| 402 |
{ |
| 403 |
'content': 'haxed you, bro', |
| 404 |
'pub_date': '2026-09-16T18:36:15', |
| 405 |
'user': 2, |
| 406 |
'id': 2 |
| 407 |
} |
| 408 |
|
| 409 |
This is a problem -- we need a way of ensuring that users can only edit their |
| 410 |
own messages. Furthermore, when they create messages we need to make sure the |
| 411 |
message is assigned to them. |
| 412 |
|
| 413 |
|
| 414 |
Restricting API access on a per-model basis |
| 415 |
------------------------------------------- |
| 416 |
|
| 417 |
flask-peewee comes with a special subclass of :py:class:`RestResource` that |
| 418 |
restricts POST/PUT/DELETE requests to prevent users from modifying another user's |
| 419 |
content. |
| 420 |
|
| 421 |
.. code-block:: python |
| 422 |
|
| 423 |
from flask_peewee.rest import RestrictOwnerResource |
| 424 |
|
| 425 |
|
| 426 |
class MessageResource(RestrictOwnerResource): |
| 427 |
owner_field = 'user' |
| 428 |
|
| 429 |
api.register(Message, MessageResource) |
| 430 |
|
| 431 |
Now, if we try and modify the message, we get a 403 Forbidden: |
| 432 |
|
| 433 |
.. code-block:: python |
| 434 |
|
| 435 |
resp = requests.put( |
| 436 |
'http://127.0.0.1:5000/api/message/2/', |
| 437 |
json={'content': 'haxed you, bro'}, |
| 438 |
auth=('admin', 'admin'), |
| 439 |
) |
| 440 |
print(resp.status_code) # 403 |
| 441 |
|
| 442 |
It is fine to modify our own message, though (message with id=1): |
| 443 |
|
| 444 |
.. code-block:: python |
| 445 |
|
| 446 |
resp = requests.put( |
| 447 |
'http://127.0.0.1:5000/api/message/1/', |
| 448 |
json={'content': 'haxed you, bro'}, |
| 449 |
auth=('admin', 'admin'), |
| 450 |
) |
| 451 |
print(resp.status_code) # 200 |
| 452 |
|
| 453 |
Under-the-hood, the `implementation <https://github.com/coleifer/flask-peewee/blob/master/flask_peewee/rest.py>`_ of the :py:class:`RestrictOwnerResource` is pretty simple. |
| 454 |
|
| 455 |
* PUT / DELETE -- verify the authenticated user is the owner of the object |
| 456 |
* POST -- assign the authenticated user as the owner of the new object |
| 457 |
|
| 458 |
|
| 459 |
Locking down a resource |
| 460 |
----------------------- |
| 461 |
|
| 462 |
Suppose we want to restrict normal users from modifying ``User`` resources. For this |
| 463 |
we can use a special subclass of :py:class:`UserAuthentication` that restricts access |
| 464 |
to administrators: |
| 465 |
|
| 466 |
.. code-block:: python |
| 467 |
|
| 468 |
from flask_peewee.rest import AdminAuthentication |
| 469 |
|
| 470 |
# instantiate our user-based auth |
| 471 |
user_auth = UserAuthentication(auth) |
| 472 |
|
| 473 |
# instantiate admin-only auth |
| 474 |
admin_auth = AdminAuthentication(auth) |
| 475 |
|
| 476 |
# instantiate our api wrapper, specifying user_auth as the default |
| 477 |
api = RestAPI(app, default_auth=user_auth) |
| 478 |
|
| 479 |
# register the UserResource with admin auth |
| 480 |
api.register(User, UserResource, auth=admin_auth) |
| 481 |
|
| 482 |
|
| 483 |
Token-based authentication |
| 484 |
-------------------------- |
| 485 |
|
| 486 |
:py:class:`UserAuthentication` and :py:class:`AdminAuthentication` use HTTP |
| 487 |
Basic auth, which is handy for humans but awkward for programmatic clients. For |
| 488 |
API clients, flask-peewee ships token-based authentication classes. Like all |
| 489 |
authentication classes they only guard the ``protected_methods`` (``POST``, |
| 490 |
``PUT`` and ``DELETE`` by default -- ``GET`` is open). To require auth on reads |
| 491 |
too, pass ``protected_methods=ALL_METHODS`` (a convenience constant equal to |
| 492 |
``('GET', 'POST', 'PUT', 'DELETE')``) or your own list. |
| 493 |
|
| 494 |
API keys |
| 495 |
^^^^^^^^ |
| 496 |
|
| 497 |
:py:class:`APIKeyAuthentication` authenticates against a model with ``key`` and |
| 498 |
``secret`` fields, supplied as query-string, header, or form parameters. The |
| 499 |
matched row is stored on ``g.api_key``: |
| 500 |
|
| 501 |
.. code-block:: python |
| 502 |
|
| 503 |
from flask_peewee.rest import APIKeyAuthentication |
| 504 |
|
| 505 |
class APIKey(db.Model): |
| 506 |
key = CharField() |
| 507 |
secret = CharField() |
| 508 |
|
| 509 |
api_key_auth = APIKeyAuthentication(APIKey) |
| 510 |
api.register(SecretModel, auth=api_key_auth) |
| 511 |
|
| 512 |
# curl "http://127.0.0.1:5000/api/secretmodel/?key=abc&secret=xyz" |
| 513 |
|
| 514 |
.. warning:: |
| 515 |
Because the key and secret can travel in the query string, they may end up |
| 516 |
in access logs. Prefer bearer tokens (below) for anything sensitive. |
| 517 |
|
| 518 |
Bearer tokens |
| 519 |
^^^^^^^^^^^^^ |
| 520 |
|
| 521 |
:py:class:`BearerAuthentication` reads a token from the standard |
| 522 |
``Authorization: Bearer <token>`` header -- so the credential stays out of the |
| 523 |
query string and logs -- and looks it up in a model with a ``token`` field. |
| 524 |
The matched row is stored on ``g.api_key``: |
| 525 |
|
| 526 |
.. code-block:: python |
| 527 |
|
| 528 |
from flask_peewee.rest import BearerAuthentication |
| 529 |
|
| 530 |
class ApiToken(db.Model): |
| 531 |
token = CharField() |
| 532 |
|
| 533 |
bearer_auth = BearerAuthentication(ApiToken) |
| 534 |
api.register(SecretModel, auth=bearer_auth) |
| 535 |
|
| 536 |
# curl -H "Authorization: Bearer <token>" http://127.0.0.1:5000/api/secretmodel/ |
| 537 |
|
| 538 |
Override ``token_field`` to use a differently-named column, and store |
| 539 |
high-entropy tokens (override ``get_key`` to keep them hashed at rest). |
| 540 |
|
| 541 |
Bearer tokens as users |
| 542 |
^^^^^^^^^^^^^^^^^^^^^^^ |
| 543 |
|
| 544 |
:py:class:`UserBearerAuthentication` resolves the token to a *user* and sets |
| 545 |
``g.user`` (rather than ``g.api_key``), so bearer tokens work with |
| 546 |
:py:class:`RestrictOwnerResource` and anything else keyed off the authenticated |
| 547 |
user. The token model carries a foreign key to the user: |
| 548 |
|
| 549 |
.. code-block:: python |
| 550 |
|
| 551 |
from flask_peewee.rest import UserBearerAuthentication |
| 552 |
|
| 553 |
class ApiToken(db.Model): |
| 554 |
token = CharField() |
| 555 |
user = ForeignKeyField(User) |
| 556 |
|
| 557 |
user_bearer_auth = UserBearerAuthentication(ApiToken) |
| 558 |
|
| 559 |
class MessageResource(RestrictOwnerResource): |
| 560 |
owner_field = 'user' |
| 561 |
|
| 562 |
api.register(Message, MessageResource, auth=user_bearer_auth) |
| 563 |
|
| 564 |
A request carrying a valid token is now treated as that token's user: new |
| 565 |
objects are assigned to them, and they may only modify their own. Set |
| 566 |
``user_field = None`` if the token lives directly on the user model instead of |
| 567 |
a separate token table. |
| 568 |
|
| 569 |
|
| 570 |
Filtering records and querying |
| 571 |
------------------------------ |
| 572 |
|
| 573 |
A REST Api is not very useful if it cannot be queried in a meaningful fashion. To |
| 574 |
this end, the flask-peewee :py:class:`RestResource` objects support "django-style" |
| 575 |
filtering: |
| 576 |
|
| 577 |
.. code-block:: console |
| 578 |
|
| 579 |
$ curl http://127.0.0.1:5000/api/message/?user=2 |
| 580 |
|
| 581 |
This call will return only messages by the ``User`` with id=2: |
| 582 |
|
| 583 |
.. code-block:: javascript |
| 584 |
|
| 585 |
{ |
| 586 |
"meta": { |
| 587 |
"model": "message", |
| 588 |
"next": "", |
| 589 |
"page": 1, |
| 590 |
"page_count": 1, |
| 591 |
"previous": "" |
| 592 |
}, |
| 593 |
"objects": [ |
| 594 |
{ |
| 595 |
"content": "haxed you, bro", |
| 596 |
"pub_date": "2026-09-16T18:36:15", |
| 597 |
"user": 2, |
| 598 |
"id": 2 |
| 599 |
} |
| 600 |
] |
| 601 |
} |
| 602 |
|
| 603 |
Joins can be traversed using the django double-underscore notation: |
| 604 |
|
| 605 |
.. code-block:: console |
| 606 |
|
| 607 |
$ curl http://127.0.0.1:5000/api/message/?user__username=admin |
| 608 |
|
| 609 |
.. code-block:: javascript |
| 610 |
|
| 611 |
{ |
| 612 |
"meta": { |
| 613 |
"model": "message", |
| 614 |
"next": "", |
| 615 |
"page": 1, |
| 616 |
"page_count": 1, |
| 617 |
"previous": "" |
| 618 |
}, |
| 619 |
"objects": [ |
| 620 |
{ |
| 621 |
"content": "flask and peewee, together at last!", |
| 622 |
"pub_date": "2026-09-16T18:36:15", |
| 623 |
"user": 1, |
| 624 |
"id": 1 |
| 625 |
}, |
| 626 |
{ |
| 627 |
"content": "hello api", |
| 628 |
"pub_date": "2026-09-22T11:25:02", |
| 629 |
"user": 1, |
| 630 |
"id": 3 |
| 631 |
} |
| 632 |
] |
| 633 |
} |
| 634 |
|
| 635 |
It is also supported to use different comparison operators with the same double-underscore notation: |
| 636 |
|
| 637 |
.. code-block:: console |
| 638 |
|
| 639 |
$ curl http://127.0.0.1:5000/api/user/?id__lt=2 |
| 640 |
|
| 641 |
.. code-block:: javascript |
| 642 |
|
| 643 |
{ |
| 644 |
"meta": { |
| 645 |
"model": "user", |
| 646 |
"next": "", |
| 647 |
"page": 1, |
| 648 |
"page_count": 1, |
| 649 |
"previous": "" |
| 650 |
}, |
| 651 |
"objects": [{ |
| 652 |
"username": "admin", |
| 653 |
"admin": true, |
| 654 |
"email": "admin@admin", |
| 655 |
"active": true, |
| 656 |
"password": "214de$25", |
| 657 |
"id": 1 |
| 658 |
}] |
| 659 |
} |
| 660 |
|
| 661 |
|
| 662 |
Valid Comparison Operators are: |
| 663 |
'eq', 'lt', 'lte', 'gt', 'gte', 'ne', 'in', 'is', 'is_not', 'like', 'ilike', 'regexp' |
| 664 |
|
| 665 |
The ``in`` operator accepts a comma-separated list and/or repeated parameters, |
| 666 |
so ``?id__in=1,2`` and ``?id__in=1&id__in=2`` are equivalent. |
| 667 |
|
| 668 |
.. note:: |
| 669 |
Unrecognized filter parameters -- a misspelled field, or a field not exposed |
| 670 |
for filtering -- are **ignored** rather than rejected, so a typo such as |
| 671 |
``?usernam=x`` silently returns every row. This is intentional: it keeps |
| 672 |
stray query-string parameters (cache-busters, tracking params, etc.) from |
| 673 |
breaking a request. Double-check your filter names if a query returns more |
| 674 |
than you expect. An unknown ``ordering`` column is likewise ignored. |
| 675 |
|
| 676 |
|
| 677 |
Restricting what can be filtered |
| 678 |
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ |
| 679 |
|
| 680 |
By default every field on the model is filterable and joins may be traversed |
| 681 |
into related models. Since filters come straight off the query string, you will |
| 682 |
often want to lock this down -- especially for sensitive columns. Three |
| 683 |
:py:class:`RestResource` attributes control it: |
| 684 |
|
| 685 |
* ``filter_fields`` -- a whitelist; only these fields may be filtered on. |
| 686 |
* ``filter_exclude`` -- a blacklist of fields that may never be filtered on (use |
| 687 |
``__`` notation for related columns, e.g. ``user__password``). |
| 688 |
* ``filter_recursive`` -- set to ``False`` to forbid filtering across foreign |
| 689 |
keys entirely (no ``user__...`` lookups at all). |
| 690 |
|
| 691 |
.. code-block:: python |
| 692 |
|
| 693 |
class MessageResource(RestResource): |
| 694 |
# the only fields a client may filter on (with any operator) |
| 695 |
filter_fields = ('id', 'content', 'user__username') |
| 696 |
|
| 697 |
class UserResource(RestResource): |
| 698 |
exclude = ('password',) # don't serialize the hash... |
| 699 |
filter_exclude = ('password',) # ...and don't let it be filtered on either |
| 700 |
|
| 701 |
Because an unrecognized filter is ignored rather than rejected (see the note |
| 702 |
above), tightening this list can never break an otherwise-valid request -- a |
| 703 |
now-disallowed filter simply stops narrowing the results. |
| 704 |
|
| 705 |
|
| 706 |
Sorting results |
| 707 |
--------------- |
| 708 |
|
| 709 |
Results can be sorted by specifying an ``ordering`` as a GET argument. The ordering |
| 710 |
must be a column on the model. |
| 711 |
|
| 712 |
`/api/message/?ordering=pub_date` |
| 713 |
|
| 714 |
If you would like to order objects "descending", place a "-" (hyphen character) before the column name: |
| 715 |
|
| 716 |
`/api/message/?ordering=-pub_date` |
| 717 |
|
| 718 |
|
| 719 |
Limiting results and pagination |
| 720 |
------------------------------- |
| 721 |
|
| 722 |
By default, resources are paginated 20 per-page (the ``paginate_by`` attribute). |
| 723 |
Specify a ``limit`` in the querystring to request a different page size -- larger |
| 724 |
or smaller: |
| 725 |
|
| 726 |
`/api/message/?limit=2` |
| 727 |
|
| 728 |
``paginate_by`` is only the default page size, not a maximum -- a client may |
| 729 |
request a larger page. To cap how large a page can be requested, set |
| 730 |
``max_paginate_by`` on the resource (it defaults to ``None``, meaning no ceiling). |
| 731 |
Setting ``paginate_by = None`` disables pagination and returns every matching |
| 732 |
object on a single page (still wrapped in the standard ``meta``/``objects`` |
| 733 |
envelope). |
| 734 |
|
| 735 |
In the "meta" section of the response, URIs for the "next" and "previous" sets |
| 736 |
of results are available, along with the total number of pages: |
| 737 |
|
| 738 |
.. code-block:: javascript |
| 739 |
|
| 740 |
"meta": { |
| 741 |
"model": "message", |
| 742 |
"next": "/api/message/?limit=1&page=3", |
| 743 |
"page": 2, |
| 744 |
"page_count": 5, |
| 745 |
"previous": "/api/message/?limit=1&page=1" |
| 746 |
} |