JVM - api.get()

Register an API route and set a specific HTTP GET handler on that route.

import io.nitric.Nitric;

class User {
  String name;
  int age;

  public User(String name, int age) {
    this.name = name;
    this.age = age;
  }
}

public class Application {
  public static void main(String[] args) {
    var api = Nitric.INSTANCE.api("public");

    api.get("/customers", (ctx) -> {
      // construct response for the GET: /customers request...
      ctx.getResp().json(User("John Smith", 31));
      return ctx;
    });

    Nitric.INSTANCE.run();
  }
}

Parameters

  • Name
    match
    Required
    Required
    Type
    String
    Description

    The path matcher to use for the route. Matchers accept path parameters in the form of a colon prefixed string. The string provided will be used as that path parameter's name when calling middleware and handlers. See create a route with path params

  • Name
    middleware
    Required
    Required
    Type
    HttpMiddleware or List<HttpMiddleware>
    Description

    One or more middleware functions to use as the handler for HTTP requests. Handlers can be sync or async

Examples

Register a handler for GET requests

import io.nitric.Nitric;

class User {
  String name;
  int age;

  public User(String name, int age) {
    this.name = name;
    this.age = age;
  }
}

public class Application {
  public static void main(String[] args) {
    var api = Nitric.INSTANCE.api("public");

    api.get("/customers", (ctx) -> {
      // construct response for the GET: /customers request...
      ctx.getResp().json(User("John Smith", 31));
      return ctx;
    });

    Nitric.INSTANCE.run();
  }
}

Chain functions as a single method handler

When multiple functions are provided they will be called as a chain. If one succeeds, it will move on to the next. This allows middleware to be composed into more complex handlers.

import io.nitric.Nitric;
import io.nitric.faas.v0.HttpContext;
import io.nitric.faas.v0.Handler;

import java.util.List;

public class Application {
  static HttpContext validateRequest(HttpContext ctx, Handler<HttpContext> next) {
    // validateRequest
    return next.invoke(ctx);
  }

  static HttpContext handleRequest(HttpContext ctx, Handler<HttpContext> next) {
    // handle request
    return next.invoke(ctx);
  }

  public static void main(String[] args) {
    var api = Nitric.INSTANCE.api("public");

    api.get("/customer", List.of(Application::validateRequest, Application::handleRequest));

    Nitric.INSTANCE.run();
  }
}