liveBook · Manning

REST controller

As explained in Clean Applications with Hexagonal Architecture

An adapter that accepts REST requests and translates them into calls to application input ports.

A controller that passes database entities through to HTTP can couple persistence, transport, and business rules. A REST controller used as an input adapter keeps HTTP at the boundary: it translates requests into commands or queries, invokes the application, and translates results into HTTP responses. section 1.2.1 section 8.5

The controller depends inward on an input port, not on its implementation. HTTP headers, JSON, and request metadata stay at the adapter. The handler behind the port orchestrates the use case and domain objects without framework annotations. section 2.2

Creating an article

An ArticleController receives a POST with article data, maps it to a CreateArticleCommand, and invokes CreateArticleUseCase. The handler looks up the author, creates a valid Article, and calls a repository output port. The controller does not decide how authors are fetched or articles stored. section 1.3 section 2.2

In a bus-based implementation, the controller can validate command inputs with validateThenCreate, dispatch through the command or query bus, and map an Either result to a success response or an API error. Request records carry data in transit; they do not themselves guarantee valid domain values. An OpenAPI schema can document constraints, but runtime enforcement requires a configured validator. section 8.5 section 9.5.4

Listing 9.31 ArticleController: The HTTP-to-core pipeline
@Slf4j
@RestController
@RequiredArgsConstructor
final class ArticleController implements ArticleApi {
 
  private final QueryBus queryBus;
  private final CommandBus commandBus;
  private final ApiErrorHandler apiErrorHandler;
 
  @Override
  public ResponseEntity<?> create(
    @RequestBody final ApiRequest.CreateArticle req,
    final HttpServletRequest request) {
    final String articleId =
      UUID.randomUUID().toString(); #A
    return CreateArticleCommand
      .validateThenCreate(articleId, req.authorId(),
        req.title(), req.content()) #B
      .flatMap(this.commandBus::execute) #C
      .mapLeft(this.apiErrorHandler::mapErrorToProblemDetail)
      .fold(
        failure -> ApiResultUtils.createFailureResponse(failure,
          URI.create(request.getRequestURI())), #D
        _ -> ApiResultUtils.createSuccessResponse(
          HttpStatus.CREATED,
          new ApiResponse.Article(articleId, req.title(),
            req.authorId(), "DRAFT"))); #E
  }
 
  @Override
  public ResponseEntity<?> find(
    @PathVariable("articleId") final String articleId,
    final HttpServletRequest request) {
    return GetArticleByIdQuery.validateThenCreate(articleId)
      .flatMap(this.queryBus::<Error, ArticleDTO,
        GetArticleByIdQuery>query) #F
      .mapLeft(this.apiErrorHandler::mapErrorToProblemDetail)
      .fold(
        failure -> ApiResultUtils.createFailureResponse(failure,
          URI.create(request.getRequestURI())),
        success -> ApiResultUtils.createSuccessResponse(
          HttpStatus.OK,
          ApiMapper.INSTANCE.toArticleResponse(success))); #G
  }
 
}

The controller pipeline generates an ID, validates command inputs, dispatches the command, and maps errors at the HTTP boundary. section 9.5.4

The controller can return an ID it generated before dispatch, even when the command handler returns Void: the ID is command input, not handler output. section 9.5.4

Test the boundary by mocking the bus and error handler, calling the controller, and asserting the response status and body. Verify that success calls the bus once without calling the error handler; for a bus failure, verify error translation. section 8.5

During migration, narrow an existing controller to translation and port invocation. Flag accumulated business logic for relocation to the handler, and compare old and port-mediated paths before removing the old path. Do not add validation rules or business conditionals to the facade. section 2.4.3

How Clean Applications with Hexagonal Architecture covers it

How deep it goes
Works through controller implementation, migration, and behavioral tests, while deferring configured runtime validation of request records.
Examples
Traces article creation from an HTTP POST through a command and handler, including a server-generated ID and error mapping.
What you can do after
Builds a REST input adapter and tests its successful and failed bus-dispatch paths.
How it connects
Connects hexagonal architecture, input ports, command and query buses, application services, and command-query separation.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Clean Applications with Hexagonal Architecture. The section links point to the parts of the book it draws on.