2
0
mirror of https://github.com/inventree/InvenTree.git synced 2025-04-28 03:26:45 +00:00

Render API docs (#6463)

* Render API docs

* Cleanup broken links

* Re-enable strict mode

* Change json to yaml

* Update docs/docs/api/schema.md

Co-authored-by: Matthias Mair <code@mjmair.com>

* Update docs/docs/api/schema.md

Co-authored-by: Matthias Mair <code@mjmair.com>

* Use neoteroi-mkdocs instead

- seems to render more reliably

* Fix SERVERS section for SPECTACTULAR_SETTINGS

* Script for splitting schema into smaller sections

* Generate an index file for the schema pages

* Move schema.md up one directory

* Fix formatting

* Remove tracked file

* Add hook for rebuilding API schema as part of RTD build

* Extract schema as RTD build step

* install invoke

* export env vars

* remove argparse

* Fix order of operations

* Compress env vars

* Remove custom env vars

- Now configured as part of RTD project

* Migrate db

* Revert "remove argparse"

This reverts commit 4665805340d068a5e17bd7f60addac930383acf5.

* Post-process generated schema file

* Fix file formatting

* Add note about schema repo

* no message

* Reduce schema overhead

* Ignore generated files

* Delete generated file

* Update .gitignore

* Add extra split for machine integration

* Remove schema files

- These will be auto-generated too

* Generate individual schema .md files

* Re-add .md files

- Need git commit log to work

* Update .gitignore

* Fix for CI test

* patch machine.api

* Revert previous change

* Formatting fix

* Adjust export step

* Bump API version

---------

Co-authored-by: Matthias Mair <code@mjmair.com>
This commit is contained in:
Oliver 2024-03-02 11:28:37 +11:00 committed by GitHub
parent d39ab9c902
commit 39ba25c5ed
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
39 changed files with 1867 additions and 33 deletions

View File

@ -144,7 +144,7 @@ jobs:
dev-install: true dev-install: true
update: true update: true
- name: Export API Documentation - name: Export API Documentation
run: invoke schema --ignore-warnings run: invoke schema --ignore-warnings --filename InvenTree/schema.yml
- name: Upload schema - name: Upload schema
uses: actions/upload-artifact@a8a3f3ad30e3422c9c7b888a15615d19a852ae32 # pin@v3.1.3 uses: actions/upload-artifact@a8a3f3ad30e3422c9c7b888a15615d19a852ae32 # pin@v3.1.3
with: with:
@ -160,7 +160,7 @@ jobs:
echo "URL: $url" echo "URL: $url"
curl -s -o api.yaml $url curl -s -o api.yaml $url
echo "Downloaded api.yaml" echo "Downloaded api.yaml"
- name: Check for differences in schemas - name: Check for differences in API Schema
if: needs.paths-filter.outputs.api == 'false' if: needs.paths-filter.outputs.api == 'false'
run: | run: |
diff --color -u InvenTree/schema.yml api.yaml diff --color -u InvenTree/schema.yml api.yaml

4
.gitignore vendored
View File

@ -104,3 +104,7 @@ api.yaml
# web frontend (static files) # web frontend (static files)
InvenTree/web/static InvenTree/web/static
# Generated docs files
docs/docs/api/*.yml
docs/docs/api/schema/*.yml

View File

@ -1,11 +1,14 @@
"""InvenTree API version information.""" """InvenTree API version information."""
# InvenTree API version # InvenTree API version
INVENTREE_API_VERSION = 179 INVENTREE_API_VERSION = 180
"""Increment this API version number whenever there is a significant change to the API that any clients need to know about.""" """Increment this API version number whenever there is a significant change to the API that any clients need to know about."""
INVENTREE_API_TEXT = """ INVENTREE_API_TEXT = """
v180 - 2024-3-02 : https://github.com/inventree/InvenTree/pull/6463
- Tweaks to API documentation to allow automatic documentation generation
v179 - 2024-03-01 : https://github.com/inventree/InvenTree/pull/6605 v179 - 2024-03-01 : https://github.com/inventree/InvenTree/pull/6605
- Adds "subcategories" count to PartCategory serializer - Adds "subcategories" count to PartCategory serializer
- Adds "sublocations" count to StockLocation serializer - Adds "sublocations" count to StockLocation serializer

View File

@ -469,21 +469,6 @@ if USE_JWT:
INSTALLED_APPS.append('rest_framework_simplejwt') INSTALLED_APPS.append('rest_framework_simplejwt')
# WSGI default setting # WSGI default setting
SPECTACULAR_SETTINGS = {
'TITLE': 'InvenTree API',
'DESCRIPTION': 'API for InvenTree - the intuitive open source inventory management system',
'LICENSE': {
'name': 'MIT',
'url': 'https://github.com/inventree/InvenTree/blob/master/LICENSE',
},
'EXTERNAL_DOCS': {
'description': 'More information about InvenTree in the official docs',
'url': 'https://docs.inventree.org',
},
'VERSION': str(inventreeApiVersion()),
'SERVE_INCLUDE_SCHEMA': False,
}
WSGI_APPLICATION = 'InvenTree.wsgi.application' WSGI_APPLICATION = 'InvenTree.wsgi.application'
""" """
@ -1208,3 +1193,23 @@ if CUSTOM_FLAGS:
# Magic login django-sesame # Magic login django-sesame
SESAME_MAX_AGE = 300 SESAME_MAX_AGE = 300
LOGIN_REDIRECT_URL = '/api/auth/login-redirect/' LOGIN_REDIRECT_URL = '/api/auth/login-redirect/'
# Configuratino for API schema generation
SPECTACULAR_SETTINGS = {
'TITLE': 'InvenTree API',
'DESCRIPTION': 'API for InvenTree - the intuitive open source inventory management system',
'LICENSE': {
'name': 'MIT',
'url': 'https://github.com/inventree/InvenTree/blob/master/LICENSE',
},
'EXTERNAL_DOCS': {
'description': 'More information about InvenTree in the official docs',
'url': 'https://docs.inventree.org',
},
'VERSION': str(inventreeApiVersion()),
'SERVE_INCLUDE_SCHEMA': False,
'SCHEMA_PATH_PREFIX': '/api/',
}
if SITE_URL:
SPECTACULAR_SETTINGS['SERVERS'] = [{'url': SITE_URL}]

View File

@ -144,7 +144,9 @@ class MachineRestart(APIView):
permission_classes = [permissions.IsAuthenticated] permission_classes = [permissions.IsAuthenticated]
@extend_schema(responses={200: MachineSerializers.MachineRestartSerializer()}) @extend_schema(
request=None, responses={200: MachineSerializers.MachineRestartSerializer()}
)
def post(self, request, pk): def post(self, request, pk):
"""Restart machine by pk.""" """Restart machine by pk."""
machine = get_machine(pk) machine = get_machine(pk)

3
docs/.gitignore vendored
View File

@ -10,6 +10,9 @@ env/
_build/ _build/
site/ site/
# Generated API schema files
docs/api/schema/*.yml
# Temp files # Temp files
releases.json releases.json
versions.json versions.json

View File

@ -17,6 +17,17 @@ The API is self-documenting, and the documentation is provided alongside any Inv
{% include 'img.html' %} {% include 'img.html' %}
{% endwith %} {% endwith %}
### Schema Description
The API schema is also documented in the [API Schema](./schema.md) page.
### Generating Schema File
If you want to generate the API schema file yourself (for example to use with an external client, use the `invoke schema` command. Run with the `-help` command to see available options.
```
invoke schema -help
```
## Authentication ## Authentication
Users must be authenticated to gain access to the InvenTree API. The API accepts either basic username:password authentication, or token authentication. Token authentication is recommended as it provides much faster API access. Users must be authenticated to gain access to the InvenTree API. The API accepts either basic username:password authentication, or token authentication. Token authentication is recommended as it provides much faster API access.

40
docs/docs/api/schema.md Normal file
View File

@ -0,0 +1,40 @@
---
title: InvenTree API Schema
---
The InvenTree API is implemented using the [Django REST framework](https://www.django-rest-framework.org).
The API schema as documented below is generated using the [drf-spectactular](https://github.com/tfranzel/drf-spectacular/) extension.
## API Version
This documentation is for API version: `171`
!!! tip "API Schema History"
We track API schema changes, and provide a snapshot of each API schema version in the [API schema repository](https://github.com/inventree/schema/).
## API Schema File
The API schema file is available for download, and can be used for generating client libraries, or for testing API endpoints.
## API Schema Documentation
API schema documentation is split into the following categories:
| Category | Description |
| --- | --- |
| [Authorization and Authentication](./schema/auth.md) | Authorization and Authentication |
| [Background Task Management](./schema/background-task.md) | Background Task Management |
| [Barcode Scanning](./schema/barcode.md) | Barcode Scanning |
| [Bill of Materials](./schema/bom.md) | Bill of Materials |
| [Build Order Management](./schema/build.md) | Build Order Management |
| [Company Management](./schema/company.md) | Company Management |
| [Label Printing](./schema/label.md) | Label Printing |
| [External Machine Management](./schema/machine.md) | External Machine Management |
| [External Order Management](./schema/order.md) | External Order Management |
| [Parts and Part Categories](./schema/part.md) | Parts and Part Categories |
| [Plugin Functionality](./schema/plugins.md) | Plugin Functionality |
| [Report Generation](./schema/report.md) | Report Generation |
| [Settings Management](./schema/settings.md) | Settings Management |
| [Stock and Stock Locations](./schema/stock.md) | Stock and Stock Locations |
| [User Management](./schema/user.md) | User Management |
| [General](./schema/general.md) | General API endpoints |

View File

@ -0,0 +1,7 @@
---
title: Authorization and Authentication
---
The *Authorization and Authentication* section of the InvenTree API schema is documented below.
[OAD(./docs/docs/api/schema/auth.yml)]

View File

@ -0,0 +1,7 @@
---
title: Background Task Management
---
The *Background Task Management* section of the InvenTree API schema is documented below.
[OAD(./docs/docs/api/schema/background-task.yml)]

View File

@ -0,0 +1,7 @@
---
title: Barcode Scanning
---
The *Barcode Scanning* section of the InvenTree API schema is documented below.
[OAD(./docs/docs/api/schema/barcode.yml)]

View File

@ -0,0 +1,7 @@
---
title: Bill of Materials
---
The *Bill of Materials* section of the InvenTree API schema is documented below.
[OAD(./docs/docs/api/schema/bom.yml)]

View File

@ -0,0 +1,7 @@
---
title: Build Order Management
---
The *Build Order Management* section of the InvenTree API schema is documented below.
[OAD(./docs/docs/api/schema/build.yml)]

View File

@ -0,0 +1,7 @@
---
title: Company Management
---
The *Company Management* section of the InvenTree API schema is documented below.
[OAD(./docs/docs/api/schema/company.yml)]

View File

@ -0,0 +1,7 @@
---
title: General API Endpoints
---
The *General API Endpoints* section of the InvenTree API schema is documented below.
[OAD(./docs/docs/api/schema/general.yml)]

View File

@ -0,0 +1,7 @@
---
title: Label Printing
---
The *Label Printing* section of the InvenTree API schema is documented below.
[OAD(./docs/docs/api/schema/label.yml)]

View File

@ -0,0 +1,7 @@
---
title: External Machine Management
---
The *External Machine Management* section of the InvenTree API schema is documented below.
[OAD(./docs/docs/api/schema/machine.yml)]

View File

@ -0,0 +1,7 @@
---
title: External Order Management
---
The *External Order Management* section of the InvenTree API schema is documented below.
[OAD(./docs/docs/api/schema/order.yml)]

View File

@ -0,0 +1,7 @@
---
title: Parts and Part Categories
---
The *Parts and Part Categories* section of the InvenTree API schema is documented below.
[OAD(./docs/docs/api/schema/part.yml)]

View File

@ -0,0 +1,7 @@
---
title: Plugin Functionality
---
The *Plugin Functionality* section of the InvenTree API schema is documented below.
[OAD(./docs/docs/api/schema/plugins.yml)]

View File

@ -0,0 +1,7 @@
---
title: Report Generation
---
The *Report Generation* section of the InvenTree API schema is documented below.
[OAD(./docs/docs/api/schema/report.yml)]

View File

@ -0,0 +1,7 @@
---
title: Settings Management
---
The *Settings Management* section of the InvenTree API schema is documented below.
[OAD(./docs/docs/api/schema/settings.yml)]

View File

@ -0,0 +1,7 @@
---
title: Stock and Stock Locations
---
The *Stock and Stock Locations* section of the InvenTree API schema is documented below.
[OAD(./docs/docs/api/schema/stock.yml)]

View File

@ -0,0 +1,7 @@
---
title: User Management
---
The *User Management* section of the InvenTree API schema is documented below.
[OAD(./docs/docs/api/schema/user.yml)]

View File

@ -48,7 +48,7 @@ The [unit of measure](../part/part.md#units-of-measure) field for the [Part](../
### Supplier Part ### Supplier Part
The [supplier part](../part/part/#supplier-parts) model uses real-world units to convert between supplier part quantities and internal stock quantities. Unit conversion rules ensure that only compatible unit types can be supplied The [supplier part](../part/part.md/#supplier-parts) model uses real-world units to convert between supplier part quantities and internal stock quantities. Unit conversion rules ensure that only compatible unit types can be supplied
### Part Parameter ### Part Parameter

View File

@ -8,7 +8,7 @@ Several models in InvenTree can be tagged with arbitrary tags. Tags are useful f
Tags are shared between all models that can be tagged. Tags are shared between all models that can be tagged.
The following models can be tagged: The following models can be tagged:
- [Parts](../../part/part.md) and [Supplier Parts](../../order/company#supplier-parts)/[Manufacturer Part](../../order/company#manufacturer-parts) - [Parts](../../part/part.md) and [Supplier Parts](../../order/company.md#supplier-parts)/[Manufacturer Part](../../order/company.md#manufacturer-parts)
- [Stock Items](../../stock/stock.md#stock-item) / [Stock Location](../../stock/stock.md#stock-location) - [Stock Items](../../stock/stock.md#stock-item) / [Stock Location](../../stock/stock.md#stock-location)

View File

@ -64,6 +64,6 @@ If the *Add Supplier Data* option is checked, then supplier part and manufacture
The following alternative methods for creating parts are supported: The following alternative methods for creating parts are supported:
- [Via the REST API](../../api/api) - [Via the REST API](../api/api.md)
- [Using the Python library](../../api/python) - [Using the Python library](../api/python/python.md)
- [Within the Admin interface](../../settings/admin) - [Within the Admin interface](../settings/admin.md)

View File

@ -7,7 +7,7 @@ title: Part Notifications
Users can select to receive notifications when certain events occur. Users can select to receive notifications when certain events occur.
!!! warning "Email Configuration Required" !!! warning "Email Configuration Required"
External notifications require correct [email configuration](../../start/config/#email-settings). They also need to be enabled in the settings under notifications`. External notifications require correct [email configuration](../start/config.md#email-settings). They also need to be enabled in the settings under notifications`.
!!! warning "Valid Email Address" !!! warning "Valid Email Address"
Each user must have a valid email address associated with their account to receive email notifications Each user must have a valid email address associated with their account to receive email notifications
@ -50,7 +50,7 @@ Any users who are subscribed to notifications for the part in question will rece
### Build Order Notification ### Build Order Notification
When a new [Build Order](../../build/build/) is created, the InvenTree software checks to see if any of the parts required to complete the order are low on stock. When a new [Build Order](../build/build.md) is created, the InvenTree software checks to see if any of the parts required to complete the order are low on stock.
If there are any parts with low stock, a notification is generated for any users subscribed to notifications for the part being built. If there are any parts with low stock, a notification is generated for any users subscribed to notifications for the part being built.

View File

@ -2,7 +2,7 @@
title: Trackable Parts title: Trackable Parts
--- ---
Denoting a part as *Trackble* changes the way that [stock items](../../stock/stock) associated with the particular part are handled in the database. A trackable part also has more restrictions imposed by the database scheme. Denoting a part as *Trackble* changes the way that [stock items](../stock/stock.md) associated with the particular part are handled in the database. A trackable part also has more restrictions imposed by the database scheme.
## Stock Tracking ## Stock Tracking

View File

@ -24,7 +24,7 @@ Refer to the [build documentation](../build/build.md#overdue-builds) for more in
### Stock Item Expiry ### Stock Item Expiry
[#1202](https://github.com/inventree/InvenTree/pull/1202) introduces the concept of an *Expiry Date* for Stock Items. For further information, refer to the [expiry documentation](../../stock/expiry). [#1202](https://github.com/inventree/InvenTree/pull/1202) introduces the concept of an *Expiry Date* for Stock Items. For further information, refer to the [expiry documentation](../stock/expiry.md).
### Stock Ownership ### Stock Ownership

View File

@ -14,7 +14,7 @@ title: Release 0.2.1
!!! warning "Configuration Required" !!! warning "Configuration Required"
Refer to the [email configuration Refer to the [email configuration
options](../../start/config/#email-settings). options](../start/config.md#email-settings).
### Manufacturer Parts ### Manufacturer Parts

View File

@ -54,7 +54,7 @@ PR [#2119](https://github.com/inventree/InvenTree/pull/2119) adds the ability to
### SSO Support ### SSO Support
PR [#2017](https://github.com/inventree/InvenTree/pull/2017) adds support for SSO (single sign on) authentication. SSO integration requires configuration by the system administrator. Refer to the [SSO documentation](../settings/sso) for further information. PR [#2017](https://github.com/inventree/InvenTree/pull/2017) adds support for SSO (single sign on) authentication. SSO integration requires configuration by the system administrator. Refer to the [SSO documentation](../settings/SSO.md) for further information.
### BOM Substitution ### BOM Substitution
@ -74,7 +74,7 @@ PR [#2208](https://github.com/inventree/InvenTree/pull/2208) provides notificati
### MFA Support ### MFA Support
PR [#2221](https://github.com/inventree/InvenTree/pull/2221) adds support for MFA (multi factor authentication). This enables admins to require all users to enable MFA as a second auth step. Refer to the [documentation](../settings/mfa) for further information. PR [#2221](https://github.com/inventree/InvenTree/pull/2221) adds support for MFA (multi factor authentication). This enables admins to require all users to enable MFA as a second auth step. Refer to the [documentation](../settings/MFA.md) for further information.
### Stock Item Forms ### Stock Item Forms
PR [#2198](https://github.com/inventree/InvenTree/pull/2198) provides a major refactor of stock item forms, for creating and editing stock items. These forms have been migrated to the REST API, providing a much more responsive user experience. PR [#2198](https://github.com/inventree/InvenTree/pull/2198) provides a major refactor of stock item forms, for creating and editing stock items. These forms have been migrated to the REST API, providing a much more responsive user experience.

View File

@ -33,7 +33,7 @@ When selecting an owner, in the drop-down list, groups are annotated with the <s
To specify the owner of a stock location, navigate to the stock location detail page. Click on the <span class='fas fa-sitemap'></span> icon under the location's name then click on "Edit Location". To specify the owner of a stock location, navigate to the stock location detail page. Click on the <span class='fas fa-sitemap'></span> icon under the location's name then click on "Edit Location".
!!! warning !!! warning
If you cannot see the <span class='fas fa-sitemap'></span> icon, it means that you do **not** have permissions to edit stock locations. Refer to [the permissions documentation](../../settings/permissions/#roles) and/or contact your InvenTree administrator. If you cannot see the <span class='fas fa-sitemap'></span> icon, it means that you do **not** have permissions to edit stock locations. Refer to [the permissions documentation](../settings/permissions.md#roles) and/or contact your InvenTree administrator.
In the "Edit Stock Location" form, select the owner and click the "Submit" button: In the "Edit Stock Location" form, select the owner and click the "Submit" button:
@ -54,7 +54,7 @@ Setting the owner of stock location will automatically:
To specify the owner of a stock item, navigate to the stock item detail page. Click on the <span class='fas fa-tools'></span> icon under the item's name then click on "Edit stock item". To specify the owner of a stock item, navigate to the stock item detail page. Click on the <span class='fas fa-tools'></span> icon under the item's name then click on "Edit stock item".
!!! warning !!! warning
If you cannot see the <span class='fas fa-tools'></span> icon, it means that you do **not** have permissions to edit stock items. Refer to [the permissions documentation](../../settings/permissions/#roles) and/or contact your InvenTree administrator. If you cannot see the <span class='fas fa-tools'></span> icon, it means that you do **not** have permissions to edit stock items. Refer to [the permissions documentation](../settings/permissions.md/#roles) and/or contact your InvenTree administrator.
In the "Edit Stock Item" form, select the owner and click the "Save" button: In the "Edit Stock Item" form, select the owner and click the "Save" button:

File diff suppressed because it is too large Load Diff

232
docs/extract_schema.py Normal file
View File

@ -0,0 +1,232 @@
"""Extract API schema and split into smaller subsections."""
import argparse
import os
import re
import textwrap
import yaml
OUTPUT_DIR = './docs/api/schema/'
# General path
GENERAL_PATH = 'general'
# List of special paths we want to split out
SPECIAL_PATHS = {
'auth': 'Authorization and Authentication',
'background-task': 'Background Task Management',
'barcode': 'Barcode Scanning',
'bom': 'Bill of Materials',
'build': 'Build Order Management',
'company': 'Company Management',
'label': 'Label Printing',
'machine': 'External Machine Management',
'order': 'External Order Management',
'part': 'Parts and Part Categories',
'plugins': 'Plugin Functionality',
'report': 'Report Generation',
'settings': 'Settings Management',
'stock': 'Stock and Stock Locations',
'user': 'User Management',
}
def top_level_path(path: str) -> str:
"""Return the top level path of the input path."""
path = path.strip()
if path.startswith('/'):
path = path[1:]
if path.endswith('/'):
path = path[:-1]
path = path.strip()
key = path.split('/')[1]
if key in SPECIAL_PATHS.keys():
return key
return GENERAL_PATH
def generate_schema_file(key: str) -> None:
"""Generate a schema file for the provided key."""
description = (
SPECIAL_PATHS[key] if key in SPECIAL_PATHS else 'General API Endpoints'
)
output = f"""
---
title: {description}
---
The *{description}* section of the InvenTree API schema is documented below.
[OAD(./docs/docs/api/schema/{key}.yml)]
"""
output = textwrap.dedent(output).strip() + '\n'
output_file = os.path.join(os.path.dirname(__file__), OUTPUT_DIR, f'{key}.md')
output_file = os.path.abspath(output_file)
print('Writing schema file to:', output_file)
with open(output_file, 'w') as f:
f.write(output)
def generate_index_file(version: str):
"""Generate the index file for the API schema."""
output = f"""
---
title: InvenTree API Schema
---
The InvenTree API is implemented using the [Django REST framework](https://www.django-rest-framework.org).
The API schema as documented below is generated using the [drf-spectactular](https://github.com/tfranzel/drf-spectacular/) extension.
## API Version
This documentation is for API version: `{version}`
!!! tip "API Schema History"
We track API schema changes, and provide a snapshot of each API schema version in the [API schema repository](https://github.com/inventree/schema/).
## API Schema File
The API schema file is available for download, and can be used for generating client libraries, or for testing API endpoints.
## API Schema Documentation
API schema documentation is split into the following categories:
| Category | Description |
| --- | --- |
"""
output = textwrap.dedent(output).strip() + '\n'
for key, value in SPECIAL_PATHS.items():
output += f'| [{value}](./schema/{key}.md) | {value} |\n'
output += '| [General](./schema/general.md) | General API endpoints |\n'
output += '\n'
output_file = os.path.join(os.path.dirname(__file__), OUTPUT_DIR, '..', 'schema.md')
print('Writing index file to:', output_file)
with open(output_file, 'w') as f:
f.write(output)
def extract_refs(data: dict, components: dict) -> list:
"""Extract a list of refs from the provided paths dict.
The refs are located like so:
<path>:<method>:responses:<status>:content:application/json:schema:$ref
Also, the referenced components might reference *sub* components,
so we need to do this step recursively.
"""
pattern = r"'?\$ref'?: '#\/components\/schemas\/(\S+)'"
# First, extract the results from the paths data dict
matches = re.findall(pattern, str(data))
refs = list(matches)
# Next, extract additional refs from the components dict
# Note that the components dict may reference other components
idx = 0
while idx < len(refs):
ref = refs[idx]
schema = components.get('schemas', {}).get(ref, None)
if schema:
# Search for additional refs
matches = re.findall(pattern, str(schema))
for match in matches:
if match not in refs:
refs.append(match)
idx += 1
# Return a dict only of the extracted refs
schemas = {ref: components['schemas'][ref] for ref in refs}
return schemas
def parse_api_file(filename: str):
"""Parse the input API file, and split into smaller sections.
The intent is to make the API schema easier to peruse on the documentation.
"""
with open(filename, 'r') as f:
data = yaml.safe_load(f)
paths = data['paths']
top_level_paths = {}
for path, methods in paths.items():
tlp = top_level_path(path)
if tlp not in top_level_paths:
top_level_paths[tlp] = {}
top_level_paths[tlp][path] = methods
# Generate output files
for key, value in top_level_paths.items():
output_file = os.path.join(os.path.dirname(__file__), OUTPUT_DIR, f'{key}.yml')
output = {}
output['paths'] = value
components = data.get('components', {})
# Extract only the schemas relating to the provided paths
path_schemas = extract_refs(value, components)
for k, v in data.items():
if k == 'components':
v = v.copy()
v['schemas'] = path_schemas
if k != 'paths':
output[k] = v
print(f'Writing schema file to {output_file}...')
output_file = os.path.abspath(output_file)
with open(output_file, 'w') as f:
yaml.dump(output, f)
# Generate a markdown file for the schema
generate_schema_file(key)
# Finally, generate an index file for the API schema
generate_index_file(data['info']['version'])
if __name__ == '__main__':
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('input', help='Input API schema file (.yml)')
args = parser.parse_args()
parse_api_file(args.input)

View File

@ -57,6 +57,7 @@ extra_css:
- stylesheets/bootstrap.css - stylesheets/bootstrap.css
- stylesheets/splide.min.css - stylesheets/splide.min.css
- stylesheets/extra.css - stylesheets/extra.css
- stylesheets/neoteroi-mkdocs.css
extra_javascript: extra_javascript:
- javascripts/extra.js - javascripts/extra.js
- javascripts/fontawesome.js - javascripts/fontawesome.js
@ -182,6 +183,7 @@ nav:
- Extend: - Extend:
- InvenTree API: - InvenTree API:
- Overview: api/api.md - Overview: api/api.md
- API Schema: api/schema.md
- Model Metadata: api/metadata.md - Model Metadata: api/metadata.md
- Download Data: api/download.md - Download Data: api/download.md
- Bulk Delete: api/bulk_delete.md - Bulk Delete: api/bulk_delete.md
@ -225,6 +227,8 @@ nav:
# Plugins # Plugins
plugins: plugins:
- neoteroi.mkdocsoad:
use_pymdownx: true
- include-markdown: - include-markdown:
opening_tag: "{!" opening_tag: "{!"
closing_tag: "!}" closing_tag: "!}"
@ -252,6 +256,8 @@ markdown_extensions:
- meta - meta
- pymdownx.details - pymdownx.details
- pymdownx.highlight - pymdownx.highlight
- pymdownx.tabbed:
alternate_style: true
- pymdownx.superfences: - pymdownx.superfences:
custom_fences: custom_fences:
- name: mermaid - name: mermaid

View File

@ -4,4 +4,5 @@ mkdocs-material>=9.0,<10.0
mkdocs-git-revision-date-localized-plugin>=1.1,<2.0 mkdocs-git-revision-date-localized-plugin>=1.1,<2.0
mkdocs-simple-hooks>=0.1,<1.0 mkdocs-simple-hooks>=0.1,<1.0
mkdocs-include-markdown-plugin mkdocs-include-markdown-plugin
neoteroi-mkdocs
mkdocstrings[python]>=0.24.0 mkdocstrings[python]>=0.24.0

View File

@ -6,8 +6,16 @@ mkdocs:
python: python:
install: install:
- requirements: docs/requirements.txt - requirements: docs/requirements.txt
- requirements: requirements.txt
build: build:
os: "ubuntu-22.04" os: "ubuntu-22.04"
tools: tools:
python: "3.9" python: "3.9"
jobs:
post_install:
- echo "Generating API schema file"
- pip install -U invoke
- invoke migrate
- invoke schema --filename docs/schema.yml --ignore-warnings
- python docs/extract_schema.py docs/schema.yml

View File

@ -918,6 +918,10 @@ def schema(c, filename='schema.yml', overwrite=False, ignore_warnings=False):
"""Export current API schema.""" """Export current API schema."""
check_file_existance(filename, overwrite) check_file_existance(filename, overwrite)
filename = os.path.abspath(filename)
print(f"Exporting schema file to '{filename}'")
cmd = f'spectacular --file {filename} --validate --color' cmd = f'spectacular --file {filename} --validate --color'
if not ignore_warnings: if not ignore_warnings:
@ -925,6 +929,10 @@ def schema(c, filename='schema.yml', overwrite=False, ignore_warnings=False):
manage(c, cmd, pty=True) manage(c, cmd, pty=True)
assert os.path.exists(filename)
print('Schema export completed:', filename)
@task(default=True) @task(default=True)
def version(c): def version(c):