6 The HTTP Server

Using the CLI

If you are creating your project using the Micronaut CLI’s create-app command, the http-server dependency is included by default.

Micronaut includes both non-blocking HTTP server and client APIs based on Netty.

The design of the HTTP server in Micronaut is optimized for interchanging messages between Microservices, typically in JSON, and is not intended as a full server-side MVC framework. For example, there is currently no support for server-side views or features typical of a traditional server-side MVC framework.

The goal of the HTTP server is to make it as easy as possible to expose APIs that can be consumed by HTTP clients, whatever language they may be written in. To use the HTTP server you must have the http-server-netty dependency on your classpath.

  1. implementation("io.micronaut:micronaut-http-server-netty")
  1. <dependency>
  2. <groupId>io.micronaut</groupId>
  3. <artifactId>micronaut-http-server-netty</artifactId>
  4. </dependency>

A “Hello World” server application can be seen below:

  1. import io.micronaut.http.MediaType;
  2. import io.micronaut.http.annotation.Controller;
  3. import io.micronaut.http.annotation.Get;
  4. @Controller("/hello") (1)
  5. public class HelloController {
  6. @Get(produces = MediaType.TEXT_PLAIN) (2)
  7. public String index() {
  8. return "Hello World"; (3)
  9. }
  10. }
  1. import io.micronaut.http.MediaType
  2. import io.micronaut.http.annotation.Controller
  3. import io.micronaut.http.annotation.Get
  4. @Controller('/hello') (1)
  5. class HelloController {
  6. @Get(produces = MediaType.TEXT_PLAIN) (2)
  7. String index() {
  8. 'Hello World' (3)
  9. }
  10. }
  1. import io.micronaut.http.MediaType
  2. import io.micronaut.http.annotation.Controller
  3. import io.micronaut.http.annotation.Get
  4. @Controller("/hello") (1)
  5. class HelloController {
  6. @Get(produces = [MediaType.TEXT_PLAIN]) (2)
  7. fun index(): String {
  8. return "Hello World" (3)
  9. }
  10. }
1The class is defined as a controller with the @Controller annotation mapped to the path /hello
2The method will respond to a GET request to /hello and returns a response with a text/plain content type
3By defining method called index, by convention the method is exposed via the /hello URI