fastapi-viewsets 0.1.2__tar.gz → 1.0.1__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- {fastapi_viewsets-0.1.2 → fastapi_viewsets-1.0.1}/LICENSE +20 -20
- fastapi_viewsets-1.0.1/PKG-INFO +336 -0
- fastapi_viewsets-1.0.1/README.md +301 -0
- fastapi_viewsets-1.0.1/fastapi_viewsets/__init__.py +270 -0
- fastapi_viewsets-1.0.1/fastapi_viewsets/async_base.py +271 -0
- fastapi_viewsets-1.0.1/fastapi_viewsets/async_utils.py +262 -0
- fastapi_viewsets-1.0.1/fastapi_viewsets/constants.py +16 -0
- fastapi_viewsets-1.0.1/fastapi_viewsets/db_conf.py +90 -0
- fastapi_viewsets-1.0.1/fastapi_viewsets/utils.py +258 -0
- fastapi_viewsets-1.0.1/fastapi_viewsets.egg-info/PKG-INFO +336 -0
- fastapi_viewsets-1.0.1/fastapi_viewsets.egg-info/SOURCES.txt +22 -0
- fastapi_viewsets-1.0.1/fastapi_viewsets.egg-info/requires.txt +15 -0
- {fastapi_viewsets-0.1.2 → fastapi_viewsets-1.0.1}/setup.cfg +7 -7
- fastapi_viewsets-1.0.1/setup.py +40 -0
- fastapi_viewsets-1.0.1/tests/test_async_base_viewset.py +340 -0
- fastapi_viewsets-1.0.1/tests/test_async_utils.py +343 -0
- fastapi_viewsets-1.0.1/tests/test_base_viewset.py +399 -0
- fastapi_viewsets-1.0.1/tests/test_db_conf.py +116 -0
- fastapi_viewsets-1.0.1/tests/test_edge_cases.py +286 -0
- fastapi_viewsets-1.0.1/tests/test_integration.py +379 -0
- fastapi_viewsets-1.0.1/tests/test_utils.py +299 -0
- fastapi_viewsets-0.1.2/PKG-INFO +0 -16
- fastapi_viewsets-0.1.2/README.md +0 -67
- fastapi_viewsets-0.1.2/fastapi_viewsets/__init__.py +0 -93
- fastapi_viewsets-0.1.2/fastapi_viewsets/db_conf.py +0 -23
- fastapi_viewsets-0.1.2/fastapi_viewsets/utils.py +0 -41
- fastapi_viewsets-0.1.2/fastapi_viewsets.egg-info/PKG-INFO +0 -16
- fastapi_viewsets-0.1.2/fastapi_viewsets.egg-info/SOURCES.txt +0 -12
- fastapi_viewsets-0.1.2/fastapi_viewsets.egg-info/requires.txt +0 -3
- fastapi_viewsets-0.1.2/setup.py +0 -19
- {fastapi_viewsets-0.1.2 → fastapi_viewsets-1.0.1}/fastapi_viewsets.egg-info/dependency_links.txt +0 -0
- {fastapi_viewsets-0.1.2 → fastapi_viewsets-1.0.1}/fastapi_viewsets.egg-info/top_level.txt +0 -0
|
@@ -1,21 +1,21 @@
|
|
|
1
|
-
MIT License
|
|
2
|
-
|
|
3
|
-
Copyright (c) 2022 Valenchits Alexander
|
|
4
|
-
|
|
5
|
-
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
-
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
-
in the Software without restriction, including without limitation the rights
|
|
8
|
-
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
-
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
-
furnished to do so, subject to the following conditions:
|
|
11
|
-
|
|
12
|
-
The above copyright notice and this permission notice shall be included in all
|
|
13
|
-
copies or substantial portions of the Software.
|
|
14
|
-
|
|
15
|
-
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
-
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
-
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
-
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
-
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
-
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2022 Valenchits Alexander
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
21
|
SOFTWARE.
|
|
@@ -0,0 +1,336 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: fastapi_viewsets
|
|
3
|
+
Version: 1.0.1
|
|
4
|
+
Summary: Package for creating endpoint
|
|
5
|
+
Home-page: https://github.com/svalench/fastapi_viewsets
|
|
6
|
+
Author: Alexander Valenchits
|
|
7
|
+
Classifier: Programming Language :: Python :: 3.9
|
|
8
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
9
|
+
Classifier: Operating System :: OS Independent
|
|
10
|
+
Requires-Python: >=3.6
|
|
11
|
+
Description-Content-Type: text/markdown
|
|
12
|
+
License-File: LICENSE
|
|
13
|
+
Requires-Dist: fastapi>=0.76.0
|
|
14
|
+
Requires-Dist: uvicorn>=0.17.6
|
|
15
|
+
Requires-Dist: SQLAlchemy>=1.4.36
|
|
16
|
+
Requires-Dist: python-dotenv>=0.19.0
|
|
17
|
+
Requires-Dist: typing-extensions>=4.0.0; python_version < "3.8"
|
|
18
|
+
Provides-Extra: test
|
|
19
|
+
Requires-Dist: pytest>=7.0.0; extra == "test"
|
|
20
|
+
Requires-Dist: pytest-asyncio>=0.21.0; extra == "test"
|
|
21
|
+
Requires-Dist: pytest-cov>=4.0.0; extra == "test"
|
|
22
|
+
Requires-Dist: httpx>=0.24.0; extra == "test"
|
|
23
|
+
Requires-Dist: faker>=18.0.0; extra == "test"
|
|
24
|
+
Requires-Dist: aiosqlite>=0.19.0; extra == "test"
|
|
25
|
+
Dynamic: author
|
|
26
|
+
Dynamic: classifier
|
|
27
|
+
Dynamic: description
|
|
28
|
+
Dynamic: description-content-type
|
|
29
|
+
Dynamic: home-page
|
|
30
|
+
Dynamic: license-file
|
|
31
|
+
Dynamic: provides-extra
|
|
32
|
+
Dynamic: requires-dist
|
|
33
|
+
Dynamic: requires-python
|
|
34
|
+
Dynamic: summary
|
|
35
|
+
|
|
36
|
+
# FastAPI ViewSets
|
|
37
|
+
|
|
38
|
+
[](https://www.python.org/downloads/)
|
|
39
|
+
[](LICENSE)
|
|
40
|
+
[](https://badge.fury.io/py/fastapi-viewsets)
|
|
41
|
+
|
|
42
|
+
A powerful package for creating REST API endpoints with FastAPI and SQLAlchemy. Automatically generates CRUD operations (Create, Read, Update, Delete) for your database models, similar to Django REST Framework's ViewSets.
|
|
43
|
+
|
|
44
|
+
## Features
|
|
45
|
+
|
|
46
|
+
- 🚀 **Automatic CRUD endpoints** - Generate REST API endpoints automatically
|
|
47
|
+
- 🔒 **OAuth2 support** - Built-in authentication protection for endpoints
|
|
48
|
+
- ⚡ **Async support** - Full async/await support for high-performance applications
|
|
49
|
+
- 📝 **Type hints** - Full type annotation support for better IDE experience
|
|
50
|
+
- 🎯 **Flexible** - Choose which HTTP methods to enable
|
|
51
|
+
- 🔧 **Easy to use** - Simple API, minimal boilerplate code
|
|
52
|
+
|
|
53
|
+
## Installation
|
|
54
|
+
|
|
55
|
+
Install the package using pip:
|
|
56
|
+
|
|
57
|
+
```bash
|
|
58
|
+
pip install fastapi-viewsets
|
|
59
|
+
```
|
|
60
|
+
|
|
61
|
+
For async support, you'll also need an async database driver:
|
|
62
|
+
|
|
63
|
+
```bash
|
|
64
|
+
# For SQLite
|
|
65
|
+
pip install aiosqlite
|
|
66
|
+
|
|
67
|
+
# For PostgreSQL
|
|
68
|
+
pip install asyncpg
|
|
69
|
+
|
|
70
|
+
# For MySQL
|
|
71
|
+
pip install aiomysql
|
|
72
|
+
```
|
|
73
|
+
|
|
74
|
+
## Quick Start
|
|
75
|
+
|
|
76
|
+
### Synchronous Example
|
|
77
|
+
|
|
78
|
+
Create a `main.py` file:
|
|
79
|
+
|
|
80
|
+
```python
|
|
81
|
+
from typing import Optional
|
|
82
|
+
from fastapi import FastAPI
|
|
83
|
+
from pydantic import BaseModel
|
|
84
|
+
from sqlalchemy import Column, Integer, String, Boolean
|
|
85
|
+
from fastapi_viewsets import BaseViewset
|
|
86
|
+
from fastapi_viewsets.db_conf import Base, get_session, engine
|
|
87
|
+
|
|
88
|
+
# Create FastAPI app
|
|
89
|
+
app = FastAPI()
|
|
90
|
+
|
|
91
|
+
# Define Pydantic schema
|
|
92
|
+
class UserSchema(BaseModel):
|
|
93
|
+
"""Pydantic Schema"""
|
|
94
|
+
id: Optional[int] = None
|
|
95
|
+
username: str
|
|
96
|
+
password: str
|
|
97
|
+
is_admin: Optional[bool] = False
|
|
98
|
+
|
|
99
|
+
class Config:
|
|
100
|
+
orm_mode = True
|
|
101
|
+
|
|
102
|
+
# Define SQLAlchemy model
|
|
103
|
+
class User(Base):
|
|
104
|
+
"""SQLAlchemy model"""
|
|
105
|
+
__tablename__ = "user"
|
|
106
|
+
|
|
107
|
+
id = Column(Integer, primary_key=True, index=True)
|
|
108
|
+
username = Column(String, unique=True)
|
|
109
|
+
password = Column(String(255))
|
|
110
|
+
is_admin = Column(Boolean, default=False)
|
|
111
|
+
|
|
112
|
+
# Create database tables
|
|
113
|
+
Base.metadata.create_all(engine)
|
|
114
|
+
|
|
115
|
+
# Create viewset
|
|
116
|
+
user_viewset = BaseViewset(
|
|
117
|
+
endpoint='/user',
|
|
118
|
+
model=User,
|
|
119
|
+
response_model=UserSchema,
|
|
120
|
+
db_session=get_session,
|
|
121
|
+
tags=['Users']
|
|
122
|
+
)
|
|
123
|
+
|
|
124
|
+
# Register all CRUD methods
|
|
125
|
+
user_viewset.register()
|
|
126
|
+
|
|
127
|
+
# Include router in FastAPI app
|
|
128
|
+
app.include_router(user_viewset)
|
|
129
|
+
```
|
|
130
|
+
|
|
131
|
+
Run the application:
|
|
132
|
+
|
|
133
|
+
```bash
|
|
134
|
+
uvicorn main:app --reload
|
|
135
|
+
```
|
|
136
|
+
|
|
137
|
+
Visit the interactive API documentation at [http://localhost:8000/docs](http://localhost:8000/docs)
|
|
138
|
+
|
|
139
|
+
### Async Example
|
|
140
|
+
|
|
141
|
+
For async support, use `AsyncBaseViewset`:
|
|
142
|
+
|
|
143
|
+
```python
|
|
144
|
+
from typing import Optional
|
|
145
|
+
from fastapi import FastAPI
|
|
146
|
+
from pydantic import BaseModel
|
|
147
|
+
from sqlalchemy import Column, Integer, String, Boolean
|
|
148
|
+
from fastapi_viewsets import AsyncBaseViewset
|
|
149
|
+
from fastapi_viewsets.db_conf import Base, get_async_session, engine
|
|
150
|
+
|
|
151
|
+
# Create FastAPI app
|
|
152
|
+
app = FastAPI()
|
|
153
|
+
|
|
154
|
+
# Define Pydantic schema
|
|
155
|
+
class UserSchema(BaseModel):
|
|
156
|
+
"""Pydantic Schema"""
|
|
157
|
+
id: Optional[int] = None
|
|
158
|
+
username: str
|
|
159
|
+
password: str
|
|
160
|
+
is_admin: Optional[bool] = False
|
|
161
|
+
|
|
162
|
+
class Config:
|
|
163
|
+
orm_mode = True
|
|
164
|
+
|
|
165
|
+
# Define SQLAlchemy model
|
|
166
|
+
class User(Base):
|
|
167
|
+
"""SQLAlchemy model"""
|
|
168
|
+
__tablename__ = "user"
|
|
169
|
+
|
|
170
|
+
id = Column(Integer, primary_key=True, index=True)
|
|
171
|
+
username = Column(String, unique=True)
|
|
172
|
+
password = Column(String(255))
|
|
173
|
+
is_admin = Column(Boolean, default=False)
|
|
174
|
+
|
|
175
|
+
# Create database tables
|
|
176
|
+
Base.metadata.create_all(engine)
|
|
177
|
+
|
|
178
|
+
# Create async viewset
|
|
179
|
+
user_viewset = AsyncBaseViewset(
|
|
180
|
+
endpoint='/user',
|
|
181
|
+
model=User,
|
|
182
|
+
response_model=UserSchema,
|
|
183
|
+
db_session=get_async_session,
|
|
184
|
+
tags=['Users']
|
|
185
|
+
)
|
|
186
|
+
|
|
187
|
+
# Register all CRUD methods
|
|
188
|
+
user_viewset.register()
|
|
189
|
+
|
|
190
|
+
# Include router in FastAPI app
|
|
191
|
+
app.include_router(user_viewset)
|
|
192
|
+
```
|
|
193
|
+
|
|
194
|
+
## Authentication Example
|
|
195
|
+
|
|
196
|
+
You can protect endpoints with OAuth2:
|
|
197
|
+
|
|
198
|
+
```python
|
|
199
|
+
from fastapi import FastAPI, Depends, HTTPException
|
|
200
|
+
from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm
|
|
201
|
+
from fastapi_viewsets import BaseViewset
|
|
202
|
+
from fastapi_viewsets.db_conf import Base, get_session, engine
|
|
203
|
+
from starlette import status
|
|
204
|
+
|
|
205
|
+
app = FastAPI()
|
|
206
|
+
|
|
207
|
+
# ... define User model and schema ...
|
|
208
|
+
|
|
209
|
+
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")
|
|
210
|
+
|
|
211
|
+
# Create protected viewset
|
|
212
|
+
protected_viewset = BaseViewset(
|
|
213
|
+
endpoint='/user',
|
|
214
|
+
model=User,
|
|
215
|
+
response_model=UserSchema,
|
|
216
|
+
db_session=get_session,
|
|
217
|
+
tags=['Protected Users']
|
|
218
|
+
)
|
|
219
|
+
|
|
220
|
+
# Register methods with authentication
|
|
221
|
+
protected_viewset.register(
|
|
222
|
+
methods=['LIST', 'POST', 'GET', 'PUT'],
|
|
223
|
+
protected_methods=['LIST', 'POST', 'GET', 'PUT'],
|
|
224
|
+
oauth_protect=oauth2_scheme
|
|
225
|
+
)
|
|
226
|
+
|
|
227
|
+
app.include_router(protected_viewset)
|
|
228
|
+
|
|
229
|
+
# Token endpoint
|
|
230
|
+
@app.post('/token')
|
|
231
|
+
def generate_token(form_data: OAuth2PasswordRequestForm = Depends()):
|
|
232
|
+
# Your token generation logic here
|
|
233
|
+
pass
|
|
234
|
+
```
|
|
235
|
+
|
|
236
|
+
## Available HTTP Methods
|
|
237
|
+
|
|
238
|
+
The following HTTP methods are supported:
|
|
239
|
+
|
|
240
|
+
- `LIST` - GET request to list all items (with pagination)
|
|
241
|
+
- `GET` - GET request to retrieve a single item by ID
|
|
242
|
+
- `POST` - POST request to create a new item
|
|
243
|
+
- `PUT` - PUT request to replace an entire item
|
|
244
|
+
- `PATCH` - PATCH request to partially update an item
|
|
245
|
+
- `DELETE` - DELETE request to delete an item
|
|
246
|
+
|
|
247
|
+
### Selecting Specific Methods
|
|
248
|
+
|
|
249
|
+
You can register only specific methods:
|
|
250
|
+
|
|
251
|
+
```python
|
|
252
|
+
user_viewset.register(methods=['LIST', 'GET', 'POST'])
|
|
253
|
+
```
|
|
254
|
+
|
|
255
|
+
## Database Configuration
|
|
256
|
+
|
|
257
|
+
### Environment Variables
|
|
258
|
+
|
|
259
|
+
Create a `.env` file in your project root:
|
|
260
|
+
|
|
261
|
+
```env
|
|
262
|
+
SQLALCHEMY_DATABASE_URL=sqlite:///path/to/db/base.db
|
|
263
|
+
```
|
|
264
|
+
|
|
265
|
+
Or for PostgreSQL:
|
|
266
|
+
|
|
267
|
+
```env
|
|
268
|
+
SQLALCHEMY_DATABASE_URL=postgresql://username:password@localhost:5432/mydatabase
|
|
269
|
+
```
|
|
270
|
+
|
|
271
|
+
For async databases, you can also specify:
|
|
272
|
+
|
|
273
|
+
```env
|
|
274
|
+
SQLALCHEMY_ASYNC_DATABASE_URL=postgresql+asyncpg://username:password@localhost:5432/mydatabase
|
|
275
|
+
```
|
|
276
|
+
|
|
277
|
+
### Supported Databases
|
|
278
|
+
|
|
279
|
+
- SQLite (synchronous and async with `aiosqlite`)
|
|
280
|
+
- PostgreSQL (synchronous and async with `asyncpg`)
|
|
281
|
+
- MySQL (synchronous and async with `aiomysql`)
|
|
282
|
+
|
|
283
|
+
For more information, see [SQLAlchemy Engine Configuration](https://docs.sqlalchemy.org/core/engines.html).
|
|
284
|
+
|
|
285
|
+
## API Reference
|
|
286
|
+
|
|
287
|
+
### BaseViewset
|
|
288
|
+
|
|
289
|
+
Synchronous viewset class for CRUD operations.
|
|
290
|
+
|
|
291
|
+
**Parameters:**
|
|
292
|
+
- `endpoint` (str): Base endpoint path (e.g., '/user')
|
|
293
|
+
- `model`: SQLAlchemy model class
|
|
294
|
+
- `response_model`: Pydantic model for response serialization
|
|
295
|
+
- `db_session` (Callable): Database session factory function
|
|
296
|
+
- `tags` (List[str]): Tags for OpenAPI documentation
|
|
297
|
+
- `allowed_methods` (List[str], optional): List of allowed methods
|
|
298
|
+
|
|
299
|
+
**Methods:**
|
|
300
|
+
- `register(methods=None, oauth_protect=None, protected_methods=None)`: Register CRUD endpoints
|
|
301
|
+
|
|
302
|
+
### AsyncBaseViewset
|
|
303
|
+
|
|
304
|
+
Asynchronous viewset class for CRUD operations.
|
|
305
|
+
|
|
306
|
+
Same parameters and methods as `BaseViewset`, but all operations are async.
|
|
307
|
+
|
|
308
|
+
## Differences Between PUT and PATCH
|
|
309
|
+
|
|
310
|
+
- **PUT**: Replaces the entire object. All fields must be provided (missing fields will be set to None).
|
|
311
|
+
- **PATCH**: Partially updates the object. Only provided fields will be updated.
|
|
312
|
+
|
|
313
|
+
## Error Handling
|
|
314
|
+
|
|
315
|
+
The library provides comprehensive error handling:
|
|
316
|
+
|
|
317
|
+
- `404 Not Found`: When an element is not found
|
|
318
|
+
- `400 Bad Request`: For validation errors and database integrity errors
|
|
319
|
+
- Detailed error messages for debugging
|
|
320
|
+
|
|
321
|
+
## Contributing
|
|
322
|
+
|
|
323
|
+
Contributions are welcome! Please feel free to submit a Pull Request.
|
|
324
|
+
|
|
325
|
+
## License
|
|
326
|
+
|
|
327
|
+
This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.
|
|
328
|
+
|
|
329
|
+
## Author
|
|
330
|
+
|
|
331
|
+
Alexander Valenchits
|
|
332
|
+
|
|
333
|
+
## Links
|
|
334
|
+
|
|
335
|
+
- [GitHub Repository](https://github.com/svalench/fastapi_viewsets)
|
|
336
|
+
- [PyPI Package](https://pypi.org/project/fastapi-viewsets/)
|
|
@@ -0,0 +1,301 @@
|
|
|
1
|
+
# FastAPI ViewSets
|
|
2
|
+
|
|
3
|
+
[](https://www.python.org/downloads/)
|
|
4
|
+
[](LICENSE)
|
|
5
|
+
[](https://badge.fury.io/py/fastapi-viewsets)
|
|
6
|
+
|
|
7
|
+
A powerful package for creating REST API endpoints with FastAPI and SQLAlchemy. Automatically generates CRUD operations (Create, Read, Update, Delete) for your database models, similar to Django REST Framework's ViewSets.
|
|
8
|
+
|
|
9
|
+
## Features
|
|
10
|
+
|
|
11
|
+
- 🚀 **Automatic CRUD endpoints** - Generate REST API endpoints automatically
|
|
12
|
+
- 🔒 **OAuth2 support** - Built-in authentication protection for endpoints
|
|
13
|
+
- ⚡ **Async support** - Full async/await support for high-performance applications
|
|
14
|
+
- 📝 **Type hints** - Full type annotation support for better IDE experience
|
|
15
|
+
- 🎯 **Flexible** - Choose which HTTP methods to enable
|
|
16
|
+
- 🔧 **Easy to use** - Simple API, minimal boilerplate code
|
|
17
|
+
|
|
18
|
+
## Installation
|
|
19
|
+
|
|
20
|
+
Install the package using pip:
|
|
21
|
+
|
|
22
|
+
```bash
|
|
23
|
+
pip install fastapi-viewsets
|
|
24
|
+
```
|
|
25
|
+
|
|
26
|
+
For async support, you'll also need an async database driver:
|
|
27
|
+
|
|
28
|
+
```bash
|
|
29
|
+
# For SQLite
|
|
30
|
+
pip install aiosqlite
|
|
31
|
+
|
|
32
|
+
# For PostgreSQL
|
|
33
|
+
pip install asyncpg
|
|
34
|
+
|
|
35
|
+
# For MySQL
|
|
36
|
+
pip install aiomysql
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
## Quick Start
|
|
40
|
+
|
|
41
|
+
### Synchronous Example
|
|
42
|
+
|
|
43
|
+
Create a `main.py` file:
|
|
44
|
+
|
|
45
|
+
```python
|
|
46
|
+
from typing import Optional
|
|
47
|
+
from fastapi import FastAPI
|
|
48
|
+
from pydantic import BaseModel
|
|
49
|
+
from sqlalchemy import Column, Integer, String, Boolean
|
|
50
|
+
from fastapi_viewsets import BaseViewset
|
|
51
|
+
from fastapi_viewsets.db_conf import Base, get_session, engine
|
|
52
|
+
|
|
53
|
+
# Create FastAPI app
|
|
54
|
+
app = FastAPI()
|
|
55
|
+
|
|
56
|
+
# Define Pydantic schema
|
|
57
|
+
class UserSchema(BaseModel):
|
|
58
|
+
"""Pydantic Schema"""
|
|
59
|
+
id: Optional[int] = None
|
|
60
|
+
username: str
|
|
61
|
+
password: str
|
|
62
|
+
is_admin: Optional[bool] = False
|
|
63
|
+
|
|
64
|
+
class Config:
|
|
65
|
+
orm_mode = True
|
|
66
|
+
|
|
67
|
+
# Define SQLAlchemy model
|
|
68
|
+
class User(Base):
|
|
69
|
+
"""SQLAlchemy model"""
|
|
70
|
+
__tablename__ = "user"
|
|
71
|
+
|
|
72
|
+
id = Column(Integer, primary_key=True, index=True)
|
|
73
|
+
username = Column(String, unique=True)
|
|
74
|
+
password = Column(String(255))
|
|
75
|
+
is_admin = Column(Boolean, default=False)
|
|
76
|
+
|
|
77
|
+
# Create database tables
|
|
78
|
+
Base.metadata.create_all(engine)
|
|
79
|
+
|
|
80
|
+
# Create viewset
|
|
81
|
+
user_viewset = BaseViewset(
|
|
82
|
+
endpoint='/user',
|
|
83
|
+
model=User,
|
|
84
|
+
response_model=UserSchema,
|
|
85
|
+
db_session=get_session,
|
|
86
|
+
tags=['Users']
|
|
87
|
+
)
|
|
88
|
+
|
|
89
|
+
# Register all CRUD methods
|
|
90
|
+
user_viewset.register()
|
|
91
|
+
|
|
92
|
+
# Include router in FastAPI app
|
|
93
|
+
app.include_router(user_viewset)
|
|
94
|
+
```
|
|
95
|
+
|
|
96
|
+
Run the application:
|
|
97
|
+
|
|
98
|
+
```bash
|
|
99
|
+
uvicorn main:app --reload
|
|
100
|
+
```
|
|
101
|
+
|
|
102
|
+
Visit the interactive API documentation at [http://localhost:8000/docs](http://localhost:8000/docs)
|
|
103
|
+
|
|
104
|
+
### Async Example
|
|
105
|
+
|
|
106
|
+
For async support, use `AsyncBaseViewset`:
|
|
107
|
+
|
|
108
|
+
```python
|
|
109
|
+
from typing import Optional
|
|
110
|
+
from fastapi import FastAPI
|
|
111
|
+
from pydantic import BaseModel
|
|
112
|
+
from sqlalchemy import Column, Integer, String, Boolean
|
|
113
|
+
from fastapi_viewsets import AsyncBaseViewset
|
|
114
|
+
from fastapi_viewsets.db_conf import Base, get_async_session, engine
|
|
115
|
+
|
|
116
|
+
# Create FastAPI app
|
|
117
|
+
app = FastAPI()
|
|
118
|
+
|
|
119
|
+
# Define Pydantic schema
|
|
120
|
+
class UserSchema(BaseModel):
|
|
121
|
+
"""Pydantic Schema"""
|
|
122
|
+
id: Optional[int] = None
|
|
123
|
+
username: str
|
|
124
|
+
password: str
|
|
125
|
+
is_admin: Optional[bool] = False
|
|
126
|
+
|
|
127
|
+
class Config:
|
|
128
|
+
orm_mode = True
|
|
129
|
+
|
|
130
|
+
# Define SQLAlchemy model
|
|
131
|
+
class User(Base):
|
|
132
|
+
"""SQLAlchemy model"""
|
|
133
|
+
__tablename__ = "user"
|
|
134
|
+
|
|
135
|
+
id = Column(Integer, primary_key=True, index=True)
|
|
136
|
+
username = Column(String, unique=True)
|
|
137
|
+
password = Column(String(255))
|
|
138
|
+
is_admin = Column(Boolean, default=False)
|
|
139
|
+
|
|
140
|
+
# Create database tables
|
|
141
|
+
Base.metadata.create_all(engine)
|
|
142
|
+
|
|
143
|
+
# Create async viewset
|
|
144
|
+
user_viewset = AsyncBaseViewset(
|
|
145
|
+
endpoint='/user',
|
|
146
|
+
model=User,
|
|
147
|
+
response_model=UserSchema,
|
|
148
|
+
db_session=get_async_session,
|
|
149
|
+
tags=['Users']
|
|
150
|
+
)
|
|
151
|
+
|
|
152
|
+
# Register all CRUD methods
|
|
153
|
+
user_viewset.register()
|
|
154
|
+
|
|
155
|
+
# Include router in FastAPI app
|
|
156
|
+
app.include_router(user_viewset)
|
|
157
|
+
```
|
|
158
|
+
|
|
159
|
+
## Authentication Example
|
|
160
|
+
|
|
161
|
+
You can protect endpoints with OAuth2:
|
|
162
|
+
|
|
163
|
+
```python
|
|
164
|
+
from fastapi import FastAPI, Depends, HTTPException
|
|
165
|
+
from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm
|
|
166
|
+
from fastapi_viewsets import BaseViewset
|
|
167
|
+
from fastapi_viewsets.db_conf import Base, get_session, engine
|
|
168
|
+
from starlette import status
|
|
169
|
+
|
|
170
|
+
app = FastAPI()
|
|
171
|
+
|
|
172
|
+
# ... define User model and schema ...
|
|
173
|
+
|
|
174
|
+
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")
|
|
175
|
+
|
|
176
|
+
# Create protected viewset
|
|
177
|
+
protected_viewset = BaseViewset(
|
|
178
|
+
endpoint='/user',
|
|
179
|
+
model=User,
|
|
180
|
+
response_model=UserSchema,
|
|
181
|
+
db_session=get_session,
|
|
182
|
+
tags=['Protected Users']
|
|
183
|
+
)
|
|
184
|
+
|
|
185
|
+
# Register methods with authentication
|
|
186
|
+
protected_viewset.register(
|
|
187
|
+
methods=['LIST', 'POST', 'GET', 'PUT'],
|
|
188
|
+
protected_methods=['LIST', 'POST', 'GET', 'PUT'],
|
|
189
|
+
oauth_protect=oauth2_scheme
|
|
190
|
+
)
|
|
191
|
+
|
|
192
|
+
app.include_router(protected_viewset)
|
|
193
|
+
|
|
194
|
+
# Token endpoint
|
|
195
|
+
@app.post('/token')
|
|
196
|
+
def generate_token(form_data: OAuth2PasswordRequestForm = Depends()):
|
|
197
|
+
# Your token generation logic here
|
|
198
|
+
pass
|
|
199
|
+
```
|
|
200
|
+
|
|
201
|
+
## Available HTTP Methods
|
|
202
|
+
|
|
203
|
+
The following HTTP methods are supported:
|
|
204
|
+
|
|
205
|
+
- `LIST` - GET request to list all items (with pagination)
|
|
206
|
+
- `GET` - GET request to retrieve a single item by ID
|
|
207
|
+
- `POST` - POST request to create a new item
|
|
208
|
+
- `PUT` - PUT request to replace an entire item
|
|
209
|
+
- `PATCH` - PATCH request to partially update an item
|
|
210
|
+
- `DELETE` - DELETE request to delete an item
|
|
211
|
+
|
|
212
|
+
### Selecting Specific Methods
|
|
213
|
+
|
|
214
|
+
You can register only specific methods:
|
|
215
|
+
|
|
216
|
+
```python
|
|
217
|
+
user_viewset.register(methods=['LIST', 'GET', 'POST'])
|
|
218
|
+
```
|
|
219
|
+
|
|
220
|
+
## Database Configuration
|
|
221
|
+
|
|
222
|
+
### Environment Variables
|
|
223
|
+
|
|
224
|
+
Create a `.env` file in your project root:
|
|
225
|
+
|
|
226
|
+
```env
|
|
227
|
+
SQLALCHEMY_DATABASE_URL=sqlite:///path/to/db/base.db
|
|
228
|
+
```
|
|
229
|
+
|
|
230
|
+
Or for PostgreSQL:
|
|
231
|
+
|
|
232
|
+
```env
|
|
233
|
+
SQLALCHEMY_DATABASE_URL=postgresql://username:password@localhost:5432/mydatabase
|
|
234
|
+
```
|
|
235
|
+
|
|
236
|
+
For async databases, you can also specify:
|
|
237
|
+
|
|
238
|
+
```env
|
|
239
|
+
SQLALCHEMY_ASYNC_DATABASE_URL=postgresql+asyncpg://username:password@localhost:5432/mydatabase
|
|
240
|
+
```
|
|
241
|
+
|
|
242
|
+
### Supported Databases
|
|
243
|
+
|
|
244
|
+
- SQLite (synchronous and async with `aiosqlite`)
|
|
245
|
+
- PostgreSQL (synchronous and async with `asyncpg`)
|
|
246
|
+
- MySQL (synchronous and async with `aiomysql`)
|
|
247
|
+
|
|
248
|
+
For more information, see [SQLAlchemy Engine Configuration](https://docs.sqlalchemy.org/core/engines.html).
|
|
249
|
+
|
|
250
|
+
## API Reference
|
|
251
|
+
|
|
252
|
+
### BaseViewset
|
|
253
|
+
|
|
254
|
+
Synchronous viewset class for CRUD operations.
|
|
255
|
+
|
|
256
|
+
**Parameters:**
|
|
257
|
+
- `endpoint` (str): Base endpoint path (e.g., '/user')
|
|
258
|
+
- `model`: SQLAlchemy model class
|
|
259
|
+
- `response_model`: Pydantic model for response serialization
|
|
260
|
+
- `db_session` (Callable): Database session factory function
|
|
261
|
+
- `tags` (List[str]): Tags for OpenAPI documentation
|
|
262
|
+
- `allowed_methods` (List[str], optional): List of allowed methods
|
|
263
|
+
|
|
264
|
+
**Methods:**
|
|
265
|
+
- `register(methods=None, oauth_protect=None, protected_methods=None)`: Register CRUD endpoints
|
|
266
|
+
|
|
267
|
+
### AsyncBaseViewset
|
|
268
|
+
|
|
269
|
+
Asynchronous viewset class for CRUD operations.
|
|
270
|
+
|
|
271
|
+
Same parameters and methods as `BaseViewset`, but all operations are async.
|
|
272
|
+
|
|
273
|
+
## Differences Between PUT and PATCH
|
|
274
|
+
|
|
275
|
+
- **PUT**: Replaces the entire object. All fields must be provided (missing fields will be set to None).
|
|
276
|
+
- **PATCH**: Partially updates the object. Only provided fields will be updated.
|
|
277
|
+
|
|
278
|
+
## Error Handling
|
|
279
|
+
|
|
280
|
+
The library provides comprehensive error handling:
|
|
281
|
+
|
|
282
|
+
- `404 Not Found`: When an element is not found
|
|
283
|
+
- `400 Bad Request`: For validation errors and database integrity errors
|
|
284
|
+
- Detailed error messages for debugging
|
|
285
|
+
|
|
286
|
+
## Contributing
|
|
287
|
+
|
|
288
|
+
Contributions are welcome! Please feel free to submit a Pull Request.
|
|
289
|
+
|
|
290
|
+
## License
|
|
291
|
+
|
|
292
|
+
This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.
|
|
293
|
+
|
|
294
|
+
## Author
|
|
295
|
+
|
|
296
|
+
Alexander Valenchits
|
|
297
|
+
|
|
298
|
+
## Links
|
|
299
|
+
|
|
300
|
+
- [GitHub Repository](https://github.com/svalench/fastapi_viewsets)
|
|
301
|
+
- [PyPI Package](https://pypi.org/project/fastapi-viewsets/)
|