File: Quickstart.md

package info (click to toggle)
flask-openapi3 4.1.0-1
  • links: PTS, VCS
  • area: main
  • in suites: sid, trixie
  • size: 1,976 kB
  • sloc: python: 4,754; sh: 17; makefile: 15; javascript: 5
file content (203 lines) | stat: -rw-r--r-- 4,367 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
**`flask_openapi3`** based on [Flask](https://github.com/pallets/flask/)
and [Pydantic](https://github.com/pydantic/pydantic), So you can use it like Flask.

## A Minimal Application

Just like [Flask](https://flask.palletsprojects.com/en/latest/quickstart/#a-minimal-application), Create `hello.py`:

``` python
from flask_openapi3 import OpenAPI

app = OpenAPI(__name__)


@app.route('/')
def hello_world():
    return 'Hello, World!'


if __name__ == '__main__':
    app.run()
```

And then run it:

```shell
python hello.py
```

You will see the output information:

```
 * Serving Flask app 'just_flask' (lazy loading)
 * Environment: production
   WARNING: This is a development server. Do not use it in a production deployment.
   Use a production WSGI server instead.
 * Debug mode: off
 * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)

```

## REST API

You can use **`get`**, **`post`**, **`put`**, **`patch`**, **`delete`** REST API in `flask-openapi3`.

```python
from flask_openapi3 import OpenAPI

app = OpenAPI(__name__)


@app.get('/book')
def get_books():
    return ["book1", "book2"]


@app.post('/book')
def create_book():
    return {"message": "success"}


if __name__ == '__main__':
    app.run()
```

## APIBlueprint

[APIBlueprint](./Reference/APIBlueprint.md) based on [Flask Blueprint](https://flask.palletsprojects.com/en/latest/tutorial/views/#create-a-blueprint),
you should use **`register_api`** instead of  **`register_blueprint`**.

```python hl_lines="14"
from flask_openapi3 import OpenAPI

app = OpenAPI(__name__)

api = APIBlueprint('book', __name__, url_prefix='/api')


@api.post('/book')
def create_book():
    return {"message": "success"}


# register api
app.register_api(api)

if __name__ == '__main__':
    app.run()
```

## Nested APIBlueprint

Allow an **API Blueprint** to be registered on another **API Blueprint**.

For more information, please see [Flask Nesting Blueprints](https://flask.palletsprojects.com/en/latest/blueprints/#nesting-blueprints).

```python hl_lines="21 22"
from flask_openapi3 import OpenAPI, APIBlueprint

app = OpenAPI(__name__)

api = APIBlueprint('book', __name__, url_prefix='/api/book')
api_english = APIBlueprint('english', __name__)
api_chinese = APIBlueprint('chinese', __name__)


@api_english.post('/english')
def create_english_book():
    return {"message": "english"}


@api_chinese.post('/chinese')
def create_chinese_book():
    return {"message": "chinese"}


# register nested api
api.register_api(api_english)
api.register_api(api_chinese)
# register api
app.register_api(api)

if __name__ == '__main__':
    app.run(debug=True)
```

## APIView

[Class-based API View](./Reference/APIView.md), click [here](https://github.com/luolingchun/flask-openapi3/blob/master/examples/api_view_demo.py) for the complete example:

```python
@api_view.route("/book")
class BookListAPIView:
    a = 1

    @api_view.doc(summary="get book list")
    def get(self, query: BookQuery):
        print(self.a)
        return query.json()

    @api_view.doc(summary="create book")
    def post(self, body: BookBody):
        """description for a created book"""
        return body.json()
```

You can define a parameter named `view_kwargs` (the only parameter of the `__init__` function),
and using `view_kwargs.get` get the required keys for each.

```python
@api_view.route("/book")
class BookListAPIView:
    def __init__(self, view_kwargs=None):
        self.a = view_kwargs.get("a")
    
    def get(self):
        ...
    
    def post(self):
        ...

@api_view.route("/book/<id>")
class BookAPIView:
    def __init__(self, view_kwargs=None):
        self.b = view_kwargs.get("b")
    
    def get(self):
        ...
    
    def put(self):
        ...
    
    def delete(self):
        ...

app.register_api_view(
    api_view,
    view_kwargs={
        "a": 1,
        "b": 2
    }
)
```

## Async API

Just use `async` when defining functions. More information goes to [Using async and await — Flask Documentation](https://flask.palletsprojects.com/en/latest/async-await/).

!!! info

    You need to manually install `asgiref` using pip:
    ```bash
    pip install flask-openapi3[async]
    
    # or
    pip install asgiref
    ```

```python hl_lines="2"
@app.post('/open/api')
async def post_openapi(body: Query):
    print(body)
    return 'POST, OpenAPI!'
```