DocsController frameworks
From Spring Boot to Nexy
Nexy's modular router keeps the shape of a Spring Boot app: a @RestController is a @Controller
class, a @Service is an @Injectable injected through __init__, and a module groups them.
Bean Validation becomes Pydantic, and springdoc's OpenAPI page is built in.
Each section below shows a Spring Boot habit, then the same thing in Nexy.
Turning the modular router on
@SpringBootApplicationpublic class DemoApplication { public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); }}The root module is a field of nexyconfig.py, and nx dev serves it:
from nexy.core.models import NexyConfigModel from src.apps.app_module import AppModule class NexyConfig(NexyConfigModel): useRouter = AppModuleSpring finds its beans by scanning packages; a Nexy module lists them, so what a module serves is written in one place.
A controller
@RestController@RequestMapping("/api/hello")public class HelloController { @GetMapping public Map<String, String> hello() { return Map.of("message", "Hello"); }}The path is the first argument of @Controller, and the method name is the HTTP verb:
from nexy.decorators import Controller @Controller("/api/hello")class HelloController: async def get(self) -> dict: return {"message": "Hello"}A controller has one handler per verb, so @GetMapping and @PostMapping on one path are the
get and post methods of one class. GET /items and GET /items/{id} are two controllers.
@PathVariable and @RequestParam
@GetMapping("/api/users/{id}")public Map<String, Object> user(@PathVariable long id, @RequestParam(defaultValue = "") String fields) { return Map.of("id", id, "fields", fields);}{id} stays in the path and becomes a typed parameter; a request parameter is a parameter with a
default:
from nexy.decorators import Controller @Controller("/api/users/{id}")class UserController: async def get(self, id: int, fields: str = "") -> dict: return {"id": id, "fields": fields}A non-numeric id answers 404, and a request parameter of the wrong type 422.
@RequestBody, @Valid and ResponseEntity
public record NewItem(@NotBlank @Size(max = 100) String name, @Positive double price) {}@PostMapping("/api/items")public ResponseEntity<NewItem> create(@Valid @RequestBody NewItem item) { return ResponseEntity.status(HttpStatus.CREATED).body(item);}The record and its annotations are a Pydantic model, always validated, and @UseResponse sets the
status:
from pydantic import BaseModel, Field from nexy.decorators import Controller, UseResponse class NewItem(BaseModel): name: str = Field(min_length=1, max_length=100) price: float = Field(gt=0) @Controller("/api/items")class ItemsController: @UseResponse(status_code=201) async def post(self, item: NewItem) -> NewItem: return item@Service and constructor injection
@Servicepublic class GreetingService { public String greet(String name) { return "Hello " + name; }} @RestController@RequestMapping("/api/greet")public class GreetingController { private final GreetingService greetings; public GreetingController(GreetingService greetings) { this.greetings = greetings; } @GetMapping public Map<String, String> greet(@RequestParam String name) { return Map.of("message", greetings.greet(name)); }}@Service is @Injectable(), and the annotation of __init__ tells the container what to inject:
from nexy.decorators import Injectable @Injectable()class GreetingService: def greet(self, name: str) -> str: return f"Hello {name}"from nexy.decorators import Controller from .greeting_service import GreetingService @Controller("/api/greet")class GreetingController: def __init__(self, greetings: GreetingService) -> None: self.greetings = greetings async def get(self, name: str) -> dict: return {"message": self.greetings.greet(name)}A bean is a singleton by default, as in Spring. @RequestScope is
@Injectable(scope=Scope.REQUEST), and @Scope("prototype") is Scope.TRANSIENT. See
Dependency injection.
@Configuration classes and modules
A module lists its controllers and the services they use, and exports what other modules may inject:
from nexy.decorators import Module from .greeting_controller import GreetingControllerfrom .greeting_service import GreetingService @Module()class GreetModule: controllers = [GreetingController] providers = [GreetingService] exports = [GreetingService]The root module imports the others:
from nexy.decorators import Module from .admin.admin_module import AdminModulefrom .greet.greet_module import GreetModulefrom .health_controller import PublicHealthControllerfrom .hello.hello_controller import HelloControllerfrom .items.items_controller import ItemsControllerfrom .orders.orders_controller import OrderControllerfrom .posts.posts_module import PostsModulefrom .signup.signup_controller import SignupControllerfrom .users.user_controller import UserControllerfrom .users.users_page_controller import UsersPageControllerfrom .ws.echo_controller import EchoController @Module()class AppModule: controllers = [ HelloController, UserController, ItemsController, OrderController, SignupController, PublicHealthController, UsersPageController, EchoController, ] imports = [GreetModule, AdminModule, PostsModule]@RequestMapping on the class
@RestController@RequestMapping("/admin")public class AdminController { @GetMapping("/stats") public Map<String, Integer> stats() { return Map.of("users", 3); } @GetMapping("/health") public Map<String, String> health() { return Map.of("status", "UP"); }}A shared mapping is the prefix of a module, and each sub-path is a controller of that module:
from nexy.decorators import Controller, UseGuard from .guards import require_admin @Controller("/stats")@UseGuard(require_admin)class StatsController: async def get(self) -> dict: return {"users": 3} @Controller("/health")@UseGuard(require_admin)class HealthController: async def get(self) -> dict: return {"status": "UP"}from nexy.decorators import Module from .admin_controllers import HealthController, StatsController @Module(prefix="/admin")class AdminModule: controllers = [StatsController, HealthController]Spring Security
@BeanSecurityFilterChain filters(HttpSecurity http) throws Exception { return http.authorizeHttpRequests(auth -> auth .requestMatchers("/admin/**").hasRole("ADMIN") .anyRequest().permitAll()) .build();}A guard is a function that raises when the request may not go on. @UseGuard puts it on a
controller, or on one method, like @PreAuthorize:
from nexy.http import Header, HTTPException def require_admin(x_role: str = Header("")) -> None: if x_role != "admin": raise HTTPException(status_code=403, detail="Admins only")Filters
@Componentpublic class AppHeaderFilter extends OncePerRequestFilter { @Override protected void doFilterInternal(HttpServletRequest req, HttpServletResponse res, FilterChain chain) throws ServletException, IOException { res.setHeader("X-App", "demo"); chain.doFilter(req, res); }}A filter for every request is an ASGI middleware class, listed in nexyconfig.py:
from starlette.middleware.base import BaseHTTPMiddleware class AppHeader(BaseHTTPMiddleware): async def dispatch(self, request, call_next): response = await call_next(request) response.headers["x-app"] = "demo" return responsefrom nexy.core.models import NexyConfigModel from src.apps.app_module import AppModulefrom src.middlewares.app_header import AppHeader class NexyConfig(NexyConfigModel): useRouter = AppModule useMiddlewares = [(AppHeader, {})]A HandlerInterceptor that only runs before some controllers is a guard on them.
ResponseStatusException and @ControllerAdvice
@GetMapping("/api/orders/{id}")public Order order(@PathVariable long id) { return orders.findById(id) .orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "No such order"));}from nexy.decorators import Controllerfrom nexy.http import HTTPException ORDERS = {1: {"id": 1, "total": 42}} @Controller("/api/orders/{id}")class OrderController: async def get(self, id: int) -> dict: if id not in ORDERS: raise HTTPException(status_code=404, detail="No such order") return ORDERS[id]An API client that sends Accept: application/json gets {"detail": "No such order"} with the
status you raised; a browser gets the HTML not-found page.
Thymeleaf
@Controllerpublic class UserPageController { @GetMapping("/users") public String users(Model model) { model.addAttribute("users", List.of(new User("Ada"), new User("Alan"))); return "users"; }}<ul> <li th:each="user : ${users}" th:text="${user.name}"></li></ul>A controller returns a view the way it returns "users": useViews renders a .nexy file, and
its context is the Model:
users: prop[list]<ul> {% for user in users %} <li>{{ user.name | e }}</li> {% endfor %}</ul>from nexy import useViewsfrom nexy.decorators import Controller @Controller("/users")class UsersPageController: async def get(self): users = [{"name": "Ada"}, {"name": "Alan"}] return useViews("src/apps/users/users_view.nexy", context={"users": users})th:text escapes and {{ }} does not: escape what a visitor typed with | e. A page can also stay
a file of src/routes/, served next to the controllers.
JPA entities and repositories
@Entitypublic class Post { @Id @GeneratedValue Long id; String title; boolean published;} public interface PostRepository extends JpaRepository<Post, Long> { List<Post> findByPublishedTrue();}The entity is a SQLModel class, and the repository an injectable service around a session:
from sqlmodel import Field, SQLModel class Post(SQLModel, table=True): id: int | None = Field(default=None, primary_key=True) title: str published: bool = Falsefrom sqlmodel import Session, select from nexy.decorators import Injectablefrom src.configs.db import enginefrom src.models.post_model import Post @Injectable()class PostRepository: def find_by_published_true(self) -> list[Post]: with Session(engine) as session: return list(session.exec(select(Post).where(Post.published)))from nexy.decorators import Controller from .post_repository import PostRepository @Controller("/api/posts/published")class PublishedPostsController: def __init__(self, posts: PostRepository) -> None: self.posts = posts async def get(self) -> dict: return {"titles": [post.title for post in self.posts.find_by_published_true()]}from nexy.decorators import Module from .post_repository import PostRepositoryfrom .posts_controller import PublishedPostsController @Module()class PostsModule: controllers = [PublishedPostsController] providers = [PostRepository]Flyway or Liquibase migrations become nx migrate -m "add posts" and nx migrate --upgrade. See
Databases.
application.properties
| Spring Boot | Nexy |
|---|---|
server.port=8080 |
usePort = 8080 in nexyconfig.py |
spring.datasource.url |
DATABASE_URL in .env |
@CrossOrigin / CorsConfigurationSource |
useCORS = {"allow_origins": [...]} |
server.compression.enabled=true |
useGZip = {"minimum_size": 1000} |
springdoc.swagger-ui.path=/docs |
useDocsUrl = "/docs", on by default |
src/main/resources/static/ |
public/, served at / |
from nexy.core.models import NexyConfigModel from src.apps.app_module import AppModule class NexyConfig(NexyConfigModel): useRouter = AppModule usePort = 8080 useCORS = {"allow_origins": ["https://example.com"]} useGZip = {"minimum_size": 1000}Actuator health
management.endpoints.web.exposure.include=healthA health check is a controller like any other, here the /admin/health one above. A public one
goes in the root module:
from nexy.decorators import Controller @Controller("/health")class PublicHealthController: async def get(self) -> dict: return {"status": "UP"}@Async and @Scheduled
@Asyncpublic void sendWelcome(String email) { ... }Work that runs after the answer is a background task, taken as a parameter:
from nexy.decorators import Controller, UseResponsefrom nexy.http import BackgroundTasks def send_welcome(email: str) -> None: ... @Controller("/api/signup")class SignupController: @UseResponse(status_code=202) async def post(self, email: str, tasks: BackgroundTasks) -> dict: tasks.add_task(send_welcome, email) return {"queued": True}For @Scheduled jobs, run a scheduler such as APScheduler, or a cron job, next to nx start.
WebSockets
public class EchoHandler extends TextWebSocketHandler { @Override protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception { session.sendMessage(message); }}A socket method opens a WebSocket on the path of its controller:
from fastapi import WebSocket from nexy.decorators import Controller @Controller("/ws/echo")class EchoController: async def socket(self, websocket: WebSocket) -> None: await websocket.accept() await websocket.send_text(await websocket.receive_text())Clients connect to /ws/echo/, with the trailing slash.
Tests with MockMvc
@WebMvcTest(HelloController.class)class HelloControllerTest { @Autowired MockMvc mvc; @Test void hello() throws Exception { mvc.perform(get("/api/hello")).andExpect(jsonPath("$.message").value("Hello")); }}from fastapi.testclient import TestClient from nexy.app import app def test_hello(): assert TestClient(app).get("/api/hello").json() == {"message": "Hello"}Running
| Spring Boot | Nexy |
|---|---|
| start.spring.io | nx new, with the modular router |
./mvnw spring-boot:run with DevTools |
nx dev |
./mvnw package && java -jar app.jar |
nx build, then nx start |
./mvnw test |
nx test |
Next steps
- Modular routing
- Dependency injection
- Guards and metadata
- From NestJS to Nexy: the same router, from TypeScript