You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
feat(docs): Introduce decorator-based route mapping for REST controllers
- Added support for a declarative approach to route definition using decorators like `@GetMapping` and `@PostMapping`, enhancing code organization and type safety.
- Updated documentation to reflect changes in the `RestController` class, including examples and key benefits of the new routing method.
Copy file name to clipboardExpand all lines: docs/guide/entities-in-framework/rest-controller.md
+64-67Lines changed: 64 additions & 67 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -19,12 +19,13 @@ The `RestController` class in PySpring serves as a base class for building RESTf
19
19
20
20
### Create a Controller Class
21
21
22
-
Extend the `RestController` class and override the `register_routes()` method to define routes. Optionally, override `register_middlewares()` to add middleware.
22
+
Extend the `RestController` class and use the route mapping decorators to define your API endpoints. Optionally, override `register_middlewares()` to add middleware.
23
23
24
24
### Example:
25
25
26
26
```py
27
27
from py_spring_core import RestController
28
+
from py_spring_core import GetMapping, PostMapping
28
29
from fastapi import HTTPException
29
30
from pydantic import BaseModel
30
31
@@ -36,24 +37,23 @@ class MyController(RestController):
36
37
classConfig:
37
38
prefix ="/api/items"# Base URL prefix for this controller
38
39
39
-
defregister_routes(self):
40
-
@self.router.get("/")
41
-
defread_items():
42
-
return {"message": "List of items"}
40
+
@GetMapping("/")
41
+
defread_items(self):
42
+
return {"message": "List of items"}
43
43
44
-
@self.router.get("/{item_id}")
45
-
defread_item(item_id: int):
46
-
return {"message": f"Details for item {item_id}"}
44
+
@GetMapping("/{item_id}")
45
+
defread_item(self, item_id: int):
46
+
return {"message": f"Details for item {item_id}"}
47
47
48
-
@self.router.post("/", status_code=201)
49
-
defcreate_item(item: Item):
50
-
return item
48
+
@PostMapping("/", status_code=201)
49
+
defcreate_item(self, item: Item):
50
+
return item
51
51
```
52
52
53
53
### Key Points:
54
54
55
55
- Use the `Config` inner class to set the route prefix.
56
-
- Define routes using the `@self.router` decorator.
56
+
- Define routes using the route mapping decorators (`@GetMapping`, `@PostMapping`, etc.).
57
57
58
58
* * * * *
59
59
@@ -62,72 +62,69 @@ class MyController(RestController):
62
62
2. The `_handle_register_rest_controller()` method:
63
63
- Registers the controller with the application context.
64
64
- Initializes an `APIRouter` instance.
65
-
-Calls `register_routes()` to add routes.
65
+
-Automatically registers routes defined with decorators.
66
66
- Includes the controller's router in the main FastAPI application.
67
67
- Calls `register_middlewares()` for middleware registration.
68
68
69
69
* * * * *
70
70
71
71
### Defining Routes
72
-
Use `@self.router`decoratorsto define API endpoints inside `register_routes()`:
72
+
PySpring provides a declarative approach to route definition using decorators, similar to Spring's annotation-based routing. This provides a cleaner and more type-safe way to define API endpoints.
73
73
74
-
```py
75
-
@self.router.get("/")
76
-
defread_items():
77
-
return {"message": "List of items"}
78
-
79
-
@self.router.post("/", status_code=201)
80
-
defcreate_item(item: Item):
81
-
return item
82
-
```
83
-
### Example:
84
-
85
-
-`GET /` maps to the `read_items` method.
86
-
-`POST /` maps to the `create_item` method.
74
+
#### Available Decorators:
75
+
-`@GetMapping`: For HTTP GET requests
76
+
-`@PostMapping`: For HTTP POST requests
77
+
-`@PutMapping`: For HTTP PUT requests
78
+
-`@DeleteMapping`: For HTTP DELETE requests
79
+
-`@PatchMapping`: For HTTP PATCH requests
87
80
88
-
### FastAPI Features:
89
-
90
-
- Dependency Injection
91
-
- Request body handling
92
-
- Path parameter parsing
93
-
94
-
* * * * *
95
-
96
-
### Defining Middlewares
97
-
Override `register_middlewares()` to add middleware. Use `app.middleware()` to define custom middleware functions.
81
+
#### Example Usage:
82
+
```python
83
+
from py_spring_core import RestController
84
+
from py_spring_core import GetMapping, PostMapping, PutMapping, DeleteMapping
-**`self.app`**: The main FastAPI application instance.
119
-
-**`self.router`**: The APIRouter instance for the controller.
120
115
116
+
#### Key Benefits:
117
+
1.**Type Safety**: Decorators provide better type checking and IDE support
118
+
2.**Cleaner Code**: Route definitions are more concise and readable
119
+
3.**Automatic Registration**: Routes are automatically registered during application initialization
120
+
4.**Class-Level Prefixing**: Still supports the `Config.prefix` for base URL prefixing
121
+
5.**Preserved Metadata**: Function metadata is preserved using `functools.wraps`
121
122
122
-
### Important Considerations
123
-
1.**Class Configuration**: Use the `Config` class to define the URL prefix.
124
-
2.**Route Registration**: Ensure all routes are defined in `register_routes()` using `@self.router`.
125
-
3.**Middleware Registration**: Add middleware in `register_middlewares()` using `app.middleware()`.
126
-
4.**Dependency Injection**: In this class, you can leverage both PySpring's and FastAPI's dependency injection systems to manage dependencies efficiently.
127
-
5.**Error Handling**: Use `HTTPException` for proper error responses and integrate with PySpring's error handling mechanisms.
128
-
6.**Code Organization**: Keep controllers focused on request handling and delegate business logic to services or components.
123
+
#### Technical Details:
124
+
- Routes are stored in a static `RouteMapping.routes` dictionary
125
+
- Each route is registered with its HTTP method, path, and handler function
126
+
- Route registration happens during application initialization
127
+
- Decorators preserve function metadata for better introspection
129
128
130
-
* * * * *
131
-
132
-
### Summary
133
-
The `RestController` class helps build well-structured, maintainable, and scalable RESTful APIs in PySpring. By utilizing its features like routing, middleware support, and integration with FastAPI, developers can focus on creating efficient APIs while maintaining code clarity and modularity.
Copy file name to clipboardExpand all lines: docs/index.md
+2Lines changed: 2 additions & 0 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -39,6 +39,8 @@
39
39
40
40
-**Component Registration Validation**: The framework includes robust validation to prevent duplicate component registration and provides clear error messages for developers. This ensures that your application maintains a clean and consistent component structure.
41
41
42
+
-**Decorator-Based Route Mapping**: PySpring now supports a more declarative approach to route definition using decorators, similar to Spring's annotation-based routing. This provides a cleaner and more type-safe way to define API endpoints with better IDE support and code organization.
43
+
42
44
### Getting Started
43
45
To get started with **PySpring**, follow these steps:
0 commit comments