Skip to content
Tutorials Center
My learning

Topics

Lesson 11 of 38 ยท HTTP Server and Clients

Controllers and Routing

Map HTTP verbs and URIs to Micronaut controller methods: @Get, @Post, @Put, @Delete, path variables, query values, headers and route precedence.

A Micronaut controller is a bean whose methods answer HTTP requests. You already wrote a tiny one in Your First Controller. This lesson covers the full routing vocabulary: all the verb annotations, path variables, query parameters, request bodies, headers, how several routes with similar paths are ranked, and how to return status codes.

Because Micronaut is not installed on this site, its code is read-only. The runnable examples are Java stand-ins: a router with typed path variables that answers 400 for a bad number, and a query-string binder with defaults and optional values.

The verb annotations

Annotation HTTP method Typical use
@Get GET Read a resource or list
@Post POST Create
@Put PUT Replace
@Patch PATCH Partial update
@Delete DELETE Remove
@Head, @Options HEAD, OPTIONS Metadata, CORS preflight

Each takes an optional URI template. The final route is the controller's path joined with the method's path:

Java
@Controller("/books")
class BookController {

    @Get                       // GET /books
    List<Book> list() { ... }

    @Get("/{id}")              // GET /books/42
    Optional<Book> find(long id) { ... }

    @Post                      // POST /books
    HttpResponse<Book> create(@Body Book book) { ... }

    @Put("/{id}")              // PUT /books/42
    Book replace(long id, @Body Book book) { ... }

    @Delete("/{id}")           // DELETE /books/42
    HttpResponse<?> delete(long id) { ... }
}

Micronaut also has @Controller attributes for content types: consumes and produces on the controller set defaults for every method, and you can override them per method with @Consumes and @Produces. Unless told otherwise, controllers produce application/json.

Path variables

A URI template segment in braces binds to a parameter of the same name. Micronaut converts it to the parameter's type, so long id receives a number. If the text cannot be converted, such as /books/abc, the framework replies with 400 Bad Request before your method runs.

Java
@Get("/{authorId}/books/{bookId}")
Book byAuthor(long authorId, long bookId) { ... }

You can write @PathVariable("id") long bookId when the parameter name differs. Templates also support:

  • Optional segments: /{id}{/extra} matches with or without the extra part.
  • Regular expressions: /{id:[0-9]+} only matches digits, which is useful for telling /books/42 from /books/latest.
  • Wildcards: /{+path} captures the rest of the URL including slashes.

Query values and headers

Query string parameters use @QueryValue, headers use @Header, cookies use @CookieValue:

Java
@Get("/search{?q,page,size}")
Page<Book> search(@QueryValue String q,
                  @QueryValue(defaultValue = "0") int page,
                  @QueryValue(defaultValue = "20") int size,
                  @Nullable @Header("X-Trace-Id") String traceId) { ... }

The template {?q,page,size} is optional documentation; Micronaut binds simple parameter names without it. A parameter without a default is required: a missing value gives a 400 response. Optional<T> and @Nullable make it optional. The default value arrives already converted.

Where parameters come from

Path {id} in the URI template.
Query @QueryValue for ?q=term.
Header @Header for metadata like tokens.
Body @Body for the JSON payload.

Types are converted for you; bad values give 400.

1 / 2

Route precedence

When more than one route can match a URL, Micronaut chooses the most specific. A literal segment beats a variable, so /books/latest wins over /books/{id}. Without a regular expression, a call for /books/latest would otherwise be a conversion error for the variable route, which is why literals are checked first.

Java
@Get("/latest")       // wins for GET /books/latest
Book latest() { ... }

@Get("/{id}")         // handles other values
Book find(long id) { ... }

Two routes with the same method and an identical template are a startup error, so you cannot define an accidental duplicate.

Controller design habits

  • Keep controllers thin: bind, call a service bean, return. The service holds the logic and is easy to test without HTTP.
  • Use nouns in URIs and the verb for the action: POST /orders, not POST /createOrder.
  • Return Optional<T> or HttpResponse for lookups so that a missing resource becomes 404. A method that returns Optional.empty() replies 404 Not Found, and a method returning null for a non-optional type also becomes 404 with an empty body.
  • Version APIs with a path prefix such as /api/v1 set on the controller.

Stand-in 1: a router with typed path variables

The router below supports verbs, literal segments, variables with a declared type (int, string) and the literal-before-variable rule. Conversion failure gives 400 and no route gives 404; a path that exists under another verb gives 405. This imitates the behavior of Micronaut's router; its real implementation is more general.

Java Verbs, variables and precedence

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Stand-in 2: binding query parameters

A controller method signature is effectively a contract: names, types, defaults and nullability. The binder below reads a raw query string and a signature description, and either produces typed arguments or reports what is missing, much as @QueryValue(defaultValue = "..."), Optional and required parameters behave.

Java Query binding with defaults

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Putting it together

A realistic search endpoint combines a literal route, query values with defaults and a service call. The next lesson turns to the other side of the contract: reading request bodies and building responses with status codes, headers and errors in Request Binding and Responses.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Given @Get("/latest") and @Get("/{id}") in the same controller, which handles GET /books/latest?

    More specific routes with literal segments win over variable segments.
  2. 2. A request to /books/abc reaches a route with a long id. What does the client get?

    Micronaut converts the segment to the declared type and rejects values it cannot convert.
  3. 3. How do you make a query parameter optional?

    Without a default or nullability, a missing parameter is a 400 error.
  4. 4. Which annotation reads a request header into a parameter?

    @Header binds a named header; @QueryValue reads the query string and @Body the payload.

Summary

  • @Get, @Post, @Put, @Patch and @Delete map verbs; the controller path prefixes each method path.
  • segments bind to typed parameters; conversion failures give 400.
  • @QueryValue, @Header, @CookieValue and @Body bind other parts of the request.
  • Literal routes beat variable routes, so order in the file does not matter.
  • Keep controllers thin and delegate logic to services.

Next: Request Binding and Responses