Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/kemingy/defspec
Create the OpenAPI spec and document from dataclass, attrs, etc.
https://github.com/kemingy/defspec
openapi openapi-spec redoc scalar swagger
Last synced: 9 days ago
JSON representation
Create the OpenAPI spec and document from dataclass, attrs, etc.
- Host: GitHub
- URL: https://github.com/kemingy/defspec
- Owner: kemingy
- License: apache-2.0
- Created: 2024-01-19T14:09:52.000Z (10 months ago)
- Default Branch: main
- Last Pushed: 2024-03-12T02:49:49.000Z (8 months ago)
- Last Synced: 2024-10-31T07:51:33.902Z (16 days ago)
- Topics: openapi, openapi-spec, redoc, scalar, swagger
- Language: Python
- Homepage:
- Size: 26.4 KB
- Stars: 5
- Watchers: 2
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# defspec
Create the OpenAPI spec and document from `dataclass`, `attrs`, `msgspec`, etc.
## Why not ...
> [!NOTE]
> There are also lots of other projects can generate the OpenAPI document or even validate the data. This project is **not** intended to replace them.This project is a legacy of a private initiative. During the development, I discovered that using [`msgspec`](https://github.com/jcrist/msgspec) could elegantly define and generate the API schema. The OpenAPI component can be utilized to generate the API documentation for various projects. As a result, I made the decision to extract it and transform it into a public project.
You can use this project as a low-level component or a drop-in module when you don't want to introduce too many other dependencies.
## Installation
```bash
pip install defspec
```## Examples
- `flask`: [examples/flask](examples/flask_openapi.py)
- `falcon`: [examples/falcon](examples/falcon_openapi.py)You can run the above examples and open the OpenAPI document in your browser:
- `swagger`: http://127.0.0.1:8000/openapi/swagger
- `redoc`: http://127.0.0.1:8000/openapi/redoc
- `scalar`: http://127.0.0.1:8000/openapi/scalar## Usage
```python
from dataclasses import dataclass
from typing import Listfrom defspec import OpenAPI
@dataclass
class User:
name: str
age: intopenapi = OpenAPI()
openapi.register_route("/", method="get", summary="Hello World")
openapi.register_route(
"/users", method="post", summary="Get all the user info", response_type=List[User]
)# get the OpenAPI spec
print(openapi.to_dict())
# get the OpenAPI spec bytes
with open("openapi.json", "wb") as f:
f.write(openapi.to_json())# serve as a HTTP server
openapi.serve_as_http_daemon(port=8000, run_in_background=True)
```