{"id":19700048,"url":"https://github.com/emmett-framework/rest","last_synced_at":"2025-10-05T14:41:42.072Z","repository":{"id":42190534,"uuid":"234587909","full_name":"emmett-framework/rest","owner":"emmett-framework","description":"REST extension for Emmett framework","archived":false,"fork":false,"pushed_at":"2024-10-14T22:40:59.000Z","size":171,"stargazers_count":16,"open_issues_count":4,"forks_count":2,"subscribers_count":3,"default_branch":"master","last_synced_at":"2025-06-05T07:15:37.200Z","etag":null,"topics":["api","asyncio","emmett","json","python","rest"],"latest_commit_sha":null,"homepage":null,"language":"Python","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"bsd-3-clause","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/emmett-framework.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGES.md","contributing":null,"funding":".github/FUNDING.yml","license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null},"funding":{"github":["gi0baro"]}},"created_at":"2020-01-17T16:21:43.000Z","updated_at":"2025-04-09T10:15:18.000Z","dependencies_parsed_at":"2025-04-29T13:39:30.127Z","dependency_job_id":"fdc90a97-eaaf-49c1-b7f8-2b539896398b","html_url":"https://github.com/emmett-framework/rest","commit_stats":null,"previous_names":[],"tags_count":19,"template":false,"template_full_name":null,"purl":"pkg:github/emmett-framework/rest","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/emmett-framework%2Frest","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/emmett-framework%2Frest/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/emmett-framework%2Frest/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/emmett-framework%2Frest/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/emmett-framework","download_url":"https://codeload.github.com/emmett-framework/rest/tar.gz/refs/heads/master","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/emmett-framework%2Frest/sbom","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":261110612,"owners_count":23111064,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["api","asyncio","emmett","json","python","rest"],"created_at":"2024-11-11T21:02:35.024Z","updated_at":"2025-10-05T14:41:41.971Z","avatar_url":"https://github.com/emmett-framework.png","language":"Python","funding_links":["https://github.com/sponsors/gi0baro"],"categories":[],"sub_categories":[],"readme":"# Emmett-REST\n\nEmmett-REST is a REST extension for [Emmett framework](https://emmett.sh).\n\n## In a nutshell\n\n```python\nfrom emmett.orm import Model, Field\nfrom emmett_rest import REST\n\nclass Task(Model):\n    title = Field.string()\n    is_completed = Field.bool()\n\napp.use_extension(REST)\n\ntasks = app.rest_module(__name__, 'api_task', Task, url_prefix='tasks')\ntasks.query_allowed_fields = ['is_completed']\n```\n\nOutput of `http://{host}/tasks?where={\"is_completed\": false}`:\n\n```json\n{\n    \"meta\": {\n        \"object\": \"list\",\n        \"total_objects\": 1,\n        \"has_more\": false\n    },\n    \"data\": [\n        {\n            \"title\": \"Some task\",\n            \"is_completed\": false\n        }\n    ]\n}\n```\n\n## Installation\n\nYou can install Emmett-REST using pip:\n\n    pip install Emmett-REST\n\nAnd add it to your Emmett application:\n\n```python\nfrom emmett_rest import REST\n\nrest = app.use_extension(REST)\n```\n\n## Usage\n\nThe Emmett-REST extension is intended to be used with Emmett [models](https://emmett.sh/docs/latest/orm/models), and it uses application modules to build APIs over them. \n\nLet's say, for example, that you have a task manager app with a `Task` model:\n\n```python\nfrom emmett.orm import Model, Field\n\nclass Task(Model):\n    title = Field.string()\n    is_completed = Field.bool()\n    spent_time = Field.int()\n    created_at = Field.datetime()\n```\n\nThen, in order to expose REST apis for your `Task` model, you can use the `rest_module` method on your application or on any application module:\n\n```python\nfrom myapp import app, Task\n\ntasks = app.rest_module(__name__, 'api_task', Task, url_prefix='tasks')\n```\n\nAs you can see, the usage is very similar to the Emmett application modules, but we also passed the involved model to the module initialization.\n\nThis single line is enough to have a really simple REST api over the `Task` model, since under the default behaviour rest modules will expose 5 different routes:\n\n- an *index* route that will respond to `GET` requests on `/tasks` path listing all the tasks in the database\n- a *read* route that will respond to `GET` requests on `/tasks/\u003cint:rid\u003e` path returning a single task corresponding to the record id of the *rid* variable\n- a *create* route that will respond to `POST` requests on `/tasks` that will create a new task in the database\n- an *update* route that will respond to `PUT` or `PATCH` requests on `/tasks/\u003cint:rid\u003e` that will update the task corresponding to the record id of the *rid* variable\n- a *delete* route that will respond to `DELETE` requests on `/tasks/\u003cint:rid\u003e` that will delete the task corresponding to the record id of the *rid* variable.\n\nListing endpoints accepts some query parameters by default, and specifically:\n\n| parameter | default | description |\n| --- | --- | --- |\n| page | 1 | page to return |\n| page\\_size | 20 | number of records per page to return|\n| sort\\_by | id | field to sort records by (-field for desc) |\n| where | {} | json dumped string for querying |\n\n### Additional routes\n\nEmmett-REST also provides some additional not CRUD endpoints. Let's see them specifically. \n\n#### Sample route\n\nIt behaves like the *index* route, but gets records randomly. As a consequence, the `sort_by` parameter gets ignored.\n\nResponds to `GET` requests on `{base_path}/sample` endpoint, and can be activated adding `'sample'` to the enabled methods on module definition or in the extension settings.\n\n#### Grouping route\n\nResponds to `GET` requests on `{base_path}/group/\u003cstr:field\u003e` endpoint, and can be activated adding `'group'` to the enabled methods on module definition or in the extension settings.\n\nIt groups by value and count records for the given field. Results of calling `http://{host}/tasks/group/is_completed` looks like:\n\n```json\n{\n    \"meta\": {\n        \"object\": \"list\",\n        \"total_objects\": 11,\n        \"has_more\": false\n    },\n    \"data\": [\n        {\n            \"value\": true,\n            \"count\": 1\n        },\n        {\n            \"value\": false,\n            \"count\": 10\n        }\n    ]\n}\n```\n\n#### Stats route\n\nResponds to `GET` requests on `{base_path}/stats` endpoint, and can be activated adding `'stats'` to the enabled methods on module definition or in the extension settings. Parse a list of fields from the comma separated `fields` query parameter.\n\nIt return minimum, maximum and average values of the records for the specified fields. Results of calling `http://{host}/tasks/stats?fields=spent_time` looks like:\n\n```json\n{\n    \"spent_time\": {\n        \"min\": 0,\n        \"max\": 3600,\n        \"avg\": 27\n    }\n}\n```\n\n### REST module parameters\n\nThe `rest_module` method accepts several parameters (*bold ones are required*) for its configuration:\n\n| parameter | default | description |\n| --- | --- | --- |\n| **import_name** | | as for standard modules |\n| **name** | | as for standard modules |\n| **model** | | the model to use |\n| serializer | `None` | a class to be used for serialization |\n| parser | `None` | a class to be used for parsing |\n| enabled\\_methods | `str` list: index, create, read, update, delete | the routes that should be enabled on the module |\n| disabled\\_methods | `[]` | the routes that should be disabled on the module |\n| default\\_sort | `None` | the field used for sorting records by default (use model primary key unless specified) |\n| use\\_save | `True` | whether to use the `save` method in records to perform operations or the low-level ORM APIs |\n| use\\_destroy | `True` | whether to use the `destroy` method in records to perform operations or the low-level ORM APIs |\n| list\\_envelope | data | the envelope to use on the index route |\n| single\\_envelope | `False` | the envelope to use on all the routes except for lists endpoints |\n| meta\\_envelope | meta | the envelope to use for meta data |\n| groups\\_envelope | data | the envelope to use for the grouping endpoint |\n| use\\_envelope\\_on\\_parse | `False` | if set to `True` will use the envelope specified in *single_envelope* option also on parsing |\n| serialize\\_meta | `True` | whether to serialize meta data on lists endpoint |\n| base\\_path | `/` | the default path prefix for routes not involving a single record |\n| id\\_path | `/\u003cint:rid\u003e` | the default path prefix for routes involving a single record |\n| url\\_prefix | `None` | as for standard modules |\n| hostname | `None` | as for standard modules |\n| module\\_class | `RestModule` | the module class to use |\n\n### REST module properties\n\nSome of the REST module parameters needs to be configured using attributes, specifically:\n\n| attribute | description |\n| --- | --- |\n| allowed\\_sorts | list of fields that can be used with `sort_by` parameter |\n| query\\_allowed\\_fields | list of fields that can be used with `where` parameter |\n| grouping\\_allowed\\_fields | list of fields that can be used in `group` route |\n| stats\\_allowed\\_fields | list of fields that can be used in `stats` route |\n\nAn example would be:\n\n```python\ntasks.allowed_sorts = ['id', 'created_at']\ntasks.query_allowed_fields = ['is_completed']\ntasks.grouping_allowed_fields = ['is_completed']\ntasks.stats_allowed_fields ['time_spent']\n```\n\n### Customizing the database set\n\nUnder default behavior, any REST module will use `Model.all()` as the database set on every operation.\n\nWhen you need to customize it, you can use the `get_dbset` decorator. \nFor example, you may gonna use the Emmett auth module:\n\n```python\nfrom myapp import auth\n\n@tasks.get_dbset\ndef fetch_tasks():\n    return auth.user.tasks\n```\n\nor you may have some soft-deletions strategies and want to expose just the records which are not deleted:\n\n```python\n@tasks.get_dbset\ndef fetch_tasks():\n    return Task.where(lambda t: t.is_deleted == False)\n```\n\n### Customizing single row fetching\n\nUnder default behaviour, any REST module will use standard select to fetch the record on the `read` endpoint.\n\nWhen you need to customize it, you can use the `get_row` decorator.\n\nFor example, you may want to add a left join to the selection:\n\n```python\n@tasks.get_row\ndef fetch_row(dbset):\n    return dbset.select(\n        including=['many_relation'], limitby=(0, 1)\n    ).first()\n```\n\n### Customizing routed methods\n\nYou can customize every route of the REST module using its `index`, `create`, `read`, `update` and `delete` decorators. In the next examples we'll override the routes with the default ones, in order to show the original code behind the default routes.\n\n```python\nfrom emmett import request\n\n@tasks.index()\nasync def task_list(dbset):\n    pagination = tasks.get_pagination()\n    sort = tasks.get_sort()\n    rows = dbset.select(paginate=pagination, orderby=sort)\n    return tasks.serialize_many(rows, dbset, pagination)\n```\n\nAs you can see, an *index* method should accept the `dbset` parameter, that is injected by the module. This is the default one or the one you defined with the `get_dbset` decorator.\n\n```python\n@tasks.read()\nasync def task_single(row):\n    return tasks.serialize_one(row)\n```\n\nThe *read* method should accept the `row` parameter that is injected by the module. Under default behaviour the module won't call your method if it doesn't find the requested record, but instead will return a 404 HTTP response.\n\n```python\n@tasks.create()\nasync def task_new():\n    response.status = 201\n    attrs = await tasks.parse_params()\n    row = Task.new(**attrs)\n    if not row.save()::\n        response.status = 422\n        return tasks.error_422(row.validation_errors)\n    return tasks.serialize_one(row)\n```\n\nThe *create* method won't need any parameters, and is responsible of creating new records in the database.\n\n\u003e **Note:** since Emmett 2.4, a `save` method is available on records. Emmett-REST acts accordingly to the `use_save` configuration parameter (in extension configuration or module initialization), using `Model.create` when saving is disabled.\n\nThe *update* and *delete* methods are quite similar:\n\n```python\n@tasks.update()\nasync def task_edit(dbset, rid):\n    attrs = await tasks.parse_params()\n    row = dbset.where(Task.id == rid).select().first()\n    if not row:\n        response.status = 404\n        return tasks.error_404()\n    row.update(**attrs)\n    if not row.save():\n        response.status = 422\n        return tasks.error_422(row.validation_errors)\n    return tasks.serialize_one(row)\n```\n\n```python\n@tasks.delete()\nasync def task_del(dbset, rid):\n    row = dbset.where(Task.id == rid).select().first()\n    if not row or not row.destroy():\n        response.status = 404\n        return self.error_404()\n    return {}\n```\n\nsince, as you can see, they should accept the `dbset` parameter and the `rid` one, which will be the record id requested by the client.\n\n\u003e **Note:** since Emmett 2.4, `save` and `destroy` method are available on records. Emmett-REST acts accordingly to the `use_save` and `use_destroy` configuration parameter (in extension configuration or module initialization), using `dbset.update` and `dbset.delete` when saving and/or destroying is disabled.\n\nAll the decorators accept an additional `pipeline` parameter that you can use to add custom pipes to the routed function:\n\n```python\n@tasks.index(pipeline=[MyCustomPipe()])\ndef task_index:\n    # code\n```\n\n### Customizing errors\n\nYou can define custom methods for the HTTP 400, 404 and 422 errors that will generate the JSON output using the `on_400`, `on_404` and `on_422` decorators:\n\n```python\n@tasks.on_400\ndef task_400err():\n    return {'error': 'this is my 400 error'}\n\n@tasks.on_404\ndef task_404err():\n    return {'error': 'this is my 404 error'}\n    \n@tasks.on_422\ndef task_422err(errors):\n    return {'error': 422, 'validation': errors}\n```\n\n### Customizing meta generation\n\nYou can define custom method for the `meta` generation using the appropriate `meta_builder` decorator:\n\n```python\n@tasks.meta_builder\ndef _tasks_meta(self, dbset, pagination):\n    count = dbset.count()\n    page, page_size = pagination\n    total_pages = math.ceil(count / page_size)\n    return {\n        'page': page,\n        'page_prev': page - 1 if page \u003e 1 else None,\n        'page_next': page + 1 if page \u003c total_pages else None,\n        'total_pages': total_pages,\n        'total_objects': count\n    }\n```\n\n### Serialization\n\nUnder the default behaviour, the REST extension will use the `fields_rw` attribute of the involved model, and overwrite the results with the contents of the `rest_rw` attribute if present.\n\nFor example, with this model:\n\n```python\nfrom emmett.orm import Model, Field\n\nclass Task(Model):\n    title = Field.string()\n    is_completed = Field.bool()\n    created_at = Field.datetime()\n    \n    fields_rw = {\n        'id': False,\n        'created_at': False\n    }\n```\n\nthe REST extension will serialize just the *title* and the *is_completed* fields, while with this:\n\n```python\nfrom emmett.orm import Model, Field\n\nclass Task(Model):\n    title = Field.string()\n    is_completed = Field.bool()\n    created_at = Field.datetime()\n    \n    fields_rw = {\n        'id': False,\n        'created_at': False\n    }\n    \n    rest_rw = {\n        'id': True\n    }\n```\n\nthe REST extension will serialize also the *id* field.\n\n#### Serializers\n\nWhenever you need more control over the serialization, you can use the `Serializer` class of the REST extension:\n\n```python\nfrom emmett_rest import Serializer\n\nclass TaskSerializer(Serializer):\n    attributes = ['id', 'title']\n    \ntasks = app.rest_module(\n    __name__, 'api_task', Task, serializer=TaskSerializer, url_prefix='tasks')\n```\n\nSerializers are handy when you want to add custom function to serialize something present in your rows. For instance, let's say you have a very simple tagging system:\n\n```python\nfrom emmett.orm import belongs_to, has_many\n\nclass Task(Model):\n    has_many({'tags': 'TaskTag'})\n\nclass TaskTag(Model):\n    belongs_to('task')\n    name = Field.string()\n```\n\nand you want to serialize the tags as an embedded list in your task. Then you just have to add a `tags` method to your serializer:\n\n```python\nclass TaskSerializer(Serializer):\n    attributes = ['id', 'title']\n    \n    def tags(self, row):\n        return row.tags().column('name')\n```\n\nThis is the complete list of rules that the extension will take over serializers:\n\n- `attributes` is read as first step\n- the `fields_rw` and `rest_rw` attributes of the model are used to fill `attributes` list when this is empty\n- the fields in the `include` list will be added to `attributes`\n- the fields in the `exclude` list will be removed from `attributes`\n- every method defined in the serializer not starting with `_` will be called over serialization and its return value will be added to the JSON object in a key named as the method\n\nYou can also use different serialization for the list route and the other ones:\n\n```python\nfrom emmett_rest import Serializer, serialize\n\nclass TaskSerializer(Serializer):\n    attributes = ['id', 'title']\n    \nclass TaskDetailSerializer(TaskSerializer):\n    include = ['is_completed']\n    \ntasks = app.module(\n    __name__, 'api_task', Task, \n    serializer=TaskDetailSerializer, url_prefix='tasks')\n\n@tasks.index()\ndef task_list(dbset):\n    rows = dbset.select(paginate=tasks.get_pagination())\n    return serialize(rows, TaskSerializer)\n```\n\n\u003e **Note:** under default behaviour the `serialize` method will use the serializer passed to the module.\n\n### Parsing input\n\nOpposite to the serialization, you will have input parsing to parse JSON requests and perform operations on the records.\n\nUnder the default behaviour, the REST extension will use the `fields_rw` attribute of the involved model, and overwrite the results with the contents of the `rest_rw` attribute if present.\n\nFor example, with this model:\n\n```python\nfrom emmett.orm import Model, Field\n\nclass Task(Model):\n    title = Field.string()\n    is_completed = Field.bool()\n    created_at = Field.datetime()\n    \n    fields_rw = {\n        'id': False,\n        'created_at': False\n    }\n```\n\nthe REST extension will parse the input to allow just the *title* and the *is_completed* fields, while with this:\n\n```python\nfrom emmett.orm import Model, Field\n\nclass Task(Model):\n    title = Field.string()\n    is_completed = Field.bool()\n    created_at = Field.datetime()\n    \n    fields_rw = {\n        'id': False,\n        'created_at': False\n    }\n    \n    rest_rw = {\n        'id': (True, False)\n        'created_at': True\n    }\n```\n\nthe REST extension will allow also the *created_at* field.\n\n#### Parsers\n\nVery similarly to the `Serializer` class, the extension provides also a `Parser` one:\n\n```python\nfrom emmett_rest import Parser\n\nclass TaskParser(Parser):\n    attributes = ['title']\n    \ntasks = app.rest_module(\n    __name__, app, 'api_task', Task, parser=TaskParser, url_prefix='tasks')\n```\n\nAs for serializers, you can define `attributes`, `include` and `exclude` lists in a parser, and add custom methods that will parse the params:\n\n```python\nclass TaskParser(Parser):\n    attributes = ['title']\n    \n    def created_at(self, params):\n        # some code\n```\n\nand you also have the `envelope` attribute at your disposal in case you expect to have enveloped bodies over `POST`, `PUT` and `PATCH` requests:\n\n```python\nclass TaskParser(Parser):\n    envelope = \"task\"\n```\n\nThe `Parser` class also offers some decorators you might need in your code: `parse_value` and `processor`.\n\nWhile the first one might be handy in conditions where you need to edit a single attribute:\n\n```python\nclass TaskParser(Parser):\n    _completed_map = {\"yes\": True, \"no\": False}\n\n    @Parser.parse_value(\"is_completed\")\n    def parse_completed(self, value):\n        return self._completed_map[value]\n```\n\nthe latter gives you access to all the parameters and the parsed dictionary, so you can deeply customise the parsing flow:\n\n```python\nclass TaskParser(Parser):\n    @Parser.processor()\n    def custom_parsing(self, params, obj):\n        obj.status = \"completed\" if params.is_completed else \"running\"\n```\n\n### Pagination\n\nREST modules perform pagination over the listing routes under the default behaviour. This is performed with the `paginate` option during the select and the call to the `get_pagination` method.\n\nYou can customize the name of the query params or the default page sizes with the extension configuration, or you can override the method completely with subclassing.\n\n### Callbacks\n\nUnless overridden, the default `create`, `update` and `delete` methods invoke callbacks you can attach to the module using the approriate decorator. Here is the complete list:\n\n| callback | arguments| description |\n| --- | --- | --- |\n| before\\_create | `[sdict]` | called before the record insertion |\n| before\\_update | `[id\\|Row, sdict]` | called before the record gets update (when saving is disabled, the first argument is the id of the record, otherwise the record to be updated) |\n| after\\_parse\\_params | `[sdict]` | called after params are loaded from the request body |\n| after\\_create | `[Row]` | called after the record insertion |\n| after\\_update | `[Row]` | called after the record gets updated |\n| after\\_delete | `[id\\|Row]` | called after the record gets deleted (when destroying is disabled, the argument is the id of the record, otherwise the destroyed record) |\n\nFor example, you might need to notify some changes:\n\n```python\n@tasks.after_create\ndef _notify_task_creation(row):\n    my_publishing_system.notify(\n        f\"Task {row['title']} was added\"\n    )\n```\n\n### Query language\n\nThe `where` query parameter allow, within the fields specified in `query_allowed_fields`, to query records in the listing routes using a JSON object.\n\nThe query language is inspired to the MongoDB query language, and provides the following operators:\n\n| operator | argument type | description |\n| --- | --- | --- |\n| $and | `List[Dict[str, Any]]` | logical AND |\n| $or | `List[Dict[str, Any]]` | logical OR |\n| $not | `Dict[str, Any]` | logical NOT |\n| $eq | `Any` | matches specified value |\n| $ne | `Any` | inverse of $eq |\n| $in | `List[Any]` | matches any of the values in list |\n| $nin | `List[Any]` | inverse of $in |\n| $lt | `Union[int, float, str]` | matches values less than specified value |\n| $gt | `Union[int, float, str]` | matches values greater than specified value |\n| $le | `Union[int, float, str]` | matches values less than or equal to specified value |\n| $ge | `Union[int, float, str]` | matches values greater than or equal to specified value |\n| $exists | `bool` | matches not null or null values |\n| $like | `str` | matches specified like expression |\n| $ilike | `str` | case insensitive $like |\n| $contains | `str` | matches values containing specified value |\n| $icontains | `str` | case insensitive $contains |\n| $geo.contains | `GeoDict` | GIS `ST_Contains` |\n| $geo.equals | `GeoDict` | GIS `ST_Equals` |\n| $geo.intersects | `GeoDict` | GIS `ST_Intersects` |\n| $geo.overlaps | `GeoDict` | GIS `ST_Overlaps` |\n| $geo.touches | `GeoDict` | GIS `ST_Touches` |\n| $geo.within | `GeoDict` | GIS `ST_Within` |\n| $geo.dwithin | `GeoDistanceDict` | GIS `ST_DWithin` |\n\nwhere `GeoDict` indicates a dictionary with a `type` key indicating the geometry type and `coordinates` array containing the geometry points (eg: `{\"type\": \"point\", \"coordinates\": [1, 2]}`), while `GeoDistanceDict` indicates a dictionary with a `geometry` key containing a `GeoDict` and the `distance` one (eg: `{\"geometry\": {\"type\": \"point\", \"coordinates\": [1, 2]}, \"distance\": 5}`).\n\nThe JSON condition always have fields' names as keys (except for `$and`, `$or`, `$not`) and operators as values, where `$eq` is the default one:\n\n```json\n{\n    \"is_completed\": false,\n    \"priority\": {\"$gte\": 5}\n}\n```\n\n### OpenAPI schemas\n\nEmmett-REST provides utilities to automatically generate OpenAPI schemas and relevant UI.\n\nIn order to produce JSON and YAML schemas, you can instantiate a `docs` module:\n\n```python\ndocs = rest.docs_module(\n    __name__,\n    \"api_docs\",\n    title=\"My APIs\",\n    version=\"1\",\n    modules_tree_prefix=\"api.v1\"\n)\n```\n\nAs you can see, the `docs_module` methods requires a `modules_tree_prefix` parameter which instructs REST extensions which modules should be included in the schema.\n\n\u003e **Note:** ensure to define your REST modules before instantiating the OpenAPI one, as the latter will need modules to be pre-defined in order to make the inspection.\n\nThe `docs_module` method accepts several parameters (*bold ones are required*) for its configuration:\n\n| parameter | default | description |\n| --- | --- | --- |\n| **import_name** | | as for standard modules |\n| **name** | | as for standard modules |\n| **title** | | the title for the OpenAPI schema |\n| **version** | | version for the OpenAPI schema |\n| **modules\\_tree\\_prefix** | | a prefix for modules names to be included in the schema |\n| description | `None` | general description for the schema |\n| tags | `None` | tags for the schema |\n| servers | `None` | servers for the schema |\n| terms\\_of\\_service | `None` | terms of service for the schema |\n| contact | `None` | contact information for the schema |\n| license\\_info | `None` | license information for the schema |\n| security\\_schemes | `None` | security information for the schema |\n| produce\\_schemas | `False` | wheter to generate OpenAPI *schema* resources from modules serializers in addition to endpoints |\n| expose\\_ui | `None` | wheter to expose UI (under default behaviour will match the application debug flag) |\n| ui\\_path | `/docs` | path for the UI component |\n| url\\_prefix | `None` | as for standard modules |\n| hostname | `None` | as for standard modules |\n\nUnder default behaviour, Emmett-REST will generate OpenAPI schema considering your modules endpoints, inferring types from your models, serializers and parsers.\n\n#### Customising endpoints grouping\n\nUnder default behaviour, endpoints in generated OpenAPI schema are grouped by module. In case you need to change this, you can use the docs module `regroup` method:\n\n```python\ndocs.regroup(\"api.v1.some_module\", \"api.v1.another_module\")\n```\n\n#### OpenAPI modules' methods\n\nEmmett-REST provides an `openapi` object in your REST modules to enable schema customisations. Specifically, this allows you to customise naming, serializers and parsers specs for your module methods:\n\n- `RESTModule.openapi.describe.entity(name)` lets you specify a custom name for the module entity\n- `RESTModule.openapi.define.serializer(Serializer, methods)` lets you specify different serialization specs for the given methods\n- `RESTModule.openapi.define.parser(Parser, methods)` lets you specify different deserialization specs for the given methods\n\n#### OpenAPI decorators\n\nEmmett-REST provides an `openapi` decorator to allow definition of additional routes and customisation of OpenAPI schema. Let's see them in detail.\n\n##### include\n\nUsed to include a custom route in the resulting OpenAPI schema:\n\n```python\nfrom emmett_rest.openapi import openapi\n\n@mymodule.route()\n@openapi.include\nasync def custom_method():\n    ...\n```\n\n##### define\n\nUsed to specify schemes and attributes in different contexts. The `define` group provides several decorators with specific use-cases:\n\n- `openapi.define.fields` let you specify the type and default values on serializers and parsers for conditions where such data cannot be directly inferred\n- `openapi.define.request` let you specify request specs on custom endpoints\n- `openapi.define.response` let you specify response specs on custom endpoints\n- `openapi.define.response_default_errors` let you re-use standard response errors on custom endpoints\n- `openapi.define.serializer` let you re-use a `Serializer` spec on custom endpoints\n- `openapi.define.parser` let you re-use a `Parser` spec on custom endpoints\n\n##### describe\n\nUsed to describe OpenAPI schemes in different contexts. The `describe` group provides several decorators with specific use-cases:\n\n- `openapi.describe` let you specify a summary and description on custom endpoints\n- `openapi.describe.summary` let you specify a summary for custom endpoints\n- `openapi.describe.description` let you specify a description for custom endpoints\n- `openapi.describe.request` let you specify descriptions for request schemes\n- `openapi.describe.response` let you specify descriptions for response schemes\n\n### Customizing REST modules\n\n#### Extension options\n\nThis is the list of all the configuration variables available on the extension for customization – the default values are set:\n\n```python\napp.config.REST.default_module_class = RESTModule\napp.config.REST.default_serializer = Serializer\napp.config.REST.default_parser = Parser\napp.config.REST.page_param = 'page'\napp.config.REST.pagesize_param = 'page_size'\napp.config.REST.sort_param = 'sort_by'\napp.config.REST.query_param = 'where'\napp.config.REST.min_pagesize = 10\napp.config.REST.max_pagesize = 25\napp.config.REST.default_pagesize = 20\napp.config.REST.default_sort = None\napp.config.REST.base_path = '/'\napp.config.REST.id_path = '/\u003cint:rid\u003e'\napp.config.REST.list_envelope = 'data'\napp.config.REST.single_envelope = False\napp.config.REST.groups_envelope = 'data'\napp.config.REST.use_envelope_on_parse = False\napp.config.REST.serialize_meta = True\napp.config.REST.meta_envelope = 'meta'\napp.config.REST.default_enabled_methods = [\n    'index',\n    'create',\n    'read',\n    'update',\n    'delete'\n]\napp.config.REST.default_disabled_methods = []\napp.config.REST.use_save = True\napp.config.REST.use_destroy = True\n```\n\nThis configuration will be used by all the REST modules you create, unless overridden.\n\n#### Subclassing\n\nUnder the default behavior, every REST module will use the `RESTModule` class. You can create as many subclasses from this one when you need to apply the same behaviour to several modules:\n\n```python\nfrom emmett_rest import RESTModule\n\nclass MyRESTModule(RESTModule):\n    def init(self):\n        self.disabled_methods = ['delete']\n        self.index_pipeline.append(MyCustomPipe())\n        self.list_envelope = 'objects'\n        self.single_envelope = self.model.__name__.lower()\n        \n    def _get_dbset(self):\n        return self.model.where(lambda m: m.user == session.user.id)\n        \n    async def _index(self, dbset):\n        rows = dbset.select(paginate=self.get_pagination())\n        rv = self.serialize_many(rows)\n        rv['meta'] = {'total': dbset.count()}\n        return rv\n        \ntasks = app.rest_module(\n    __name__, app, 'api_task', Task, url_prefix='tasks', \n    module_class=MyRESTModule)\ntags = app.rest_module(\n    __name__, app, 'api_tag', Tag, url_prefix='tags',\n    module_class=MyRESTModule)\n```\n\nAs you can see, we defined a subclass of the `RESTModule` one and used the `init` method to customize the class initialization for our needs. We **strongly** recommend to use this method and avoid overriding the `__init__` of the class unless you really know what you're doing.\n\nUsing the `init` method, we disabled the *delete* route over the module, added a custom pipe over the *index* route and configured the envelope rules.\n\nHere is a list of variables you may want to change inside the `init` method:\n\n- model\n- serializer\n- parser\n- enabled\\_methods\n- disabled\\_methods\n- list\\_envelope\n- single\\_envelope\n- meta\\_envelope\n- groups\\_envelope\n- use\\_envelope\\_on\\_parsing\n\nAlso, this is the complete list of the pipeline variables and their default values:\n\n```python\ndef init(self):\n    self.index_pipeline = [SetFetcher(self), self._json_query_pipe]\n    self.create_pipeline = []\n    self.read_pipeline = [SetFetcher(self), RecordFetcher(self)]\n    self.update_pipeline = [SetFetcher(self)]\n    self.delete_pipeline = [SetFetcher(self)]\n    self.group_pipeline = [\n        self._group_field_pipe,\n        SetFetcher(self),\n        self._json_query_pipe\n    ]\n    self.stats_pipeline = [\n        self._stats_field_pipe,\n        SetFetcher(self),\n        self._json_query_pipe\n    ]\n    self.sample_pipeline = [SetFetcher(self), self._json_query_pipe]\n```\n\nWe've also overridden the methods for the database set retrieval and the *index* route. As you can see, these methods are starting with the `_` since are the default ones and you can still override them with decorators. This is the complete list of methods you may want to override instead of using decorators:\n\n- `_get_dbset`\n- `_get_row` \n- `_index`\n- `_create`\n- `_read`\n- `_update`\n- `_delete`\n- `_group`\n- `_stats`\n- `_sample`\n- `_build_meta`\n- `build_error_400`\n- `build_error_404`\n- `build_error_422`\n\nThere are some other methods you may need to override, like the `get_pagination` one or the serialization ones. Please, check the source code of the `RESTModule` class for further needs.\n\n## License\n\nEmmett-REST is released under BSD license. Check the LICENSE file for more details.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Femmett-framework%2Frest","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Femmett-framework%2Frest","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Femmett-framework%2Frest/lists"}