Skip to content

HttpHandler Handling Http Events

Dennis Vriend edited this page Dec 24, 2017 · 2 revisions

HttpHandler - Handling Http Events

Http requests are handled by means of API Gateway that emits Api Events. sbt-sam is instructed to wire the lambda by means of the HttpHandler annotation. sbt-sam relies heavily on play-json for all its JSON work.

Example

The following shows an example HelloWorldHandler:

import com.github.dnvriend.lambda.{ApiGatewayHandler, HttpRequest, HttpResponse, SamContext}
@HttpHandler(path = "/person", method = "get")
class HelloWorldHandler extends ApiGatewayHandler {
  override def handle(request: HttpRequest, ctx: SamContext): HttpResponse = {
    HttpResponse.ok.withBody(Json.toJson("Hello"))
  }
}

The snippet shows how to wire the 'get' method to the lambda 'HelloWorldHandler' by means of extending the ApiGatewayHandler trait. The lambda received a HttpRequest and SamContext and returns a HttpResponse, that contains a play.api.libs.json.JsValue.

Handling multiple methods

The following example shows how to handle multiple methods. It also shows how to unmarshal JSON by means of play-json and needs a Format or Reads implicit in scope. HttpRequest provides several methods to access the body of the event, but also pathParameters, requestParameters and of course the bodyAs and bodyOpt methods that try to unmarshal the payload.

object Person {
  implicit val format: Format[Person] = Json.format[Person]
}
final case class Person(name: String, id: Option[String] = None)

@HttpHandler(path = "/person", method = "post")
class PostPerson extends ApiGatewayHandler {
  override def handle(request: HttpRequest, ctx: SamContext): HttpResponse = {
    val person: Option[Person] = request.bodyOpt[Person]
    HttpResponse.ok.withBody(Json.toJson(person))
  }
}

@HttpHandler(path = "/person", method = "get")
class GetListOfPerson extends ApiGatewayHandler {
  override def handle(request: HttpRequest, ctx: SamContext): HttpResponse = {
    val repo = new PersonRepository("people", ctx)
    HttpResponse.ok.withBody(Json.toJson(repo.list))
  }
}

Handling path variables

The following example shows how to handle path variables:

@HttpHandler(path = "/person/{id}", method = "get")
class GetPerson extends ApiGatewayHandler {
  override def handle(request: HttpRequest, ctx: SamContext): HttpResponse = {
    val repo = new PersonRepository("people", ctx)
    request.pathParamsOpt[Map[String, String]].getOrElse(Map.empty).get("id")
      .fold(HttpResponse.notFound.withBody(Json.toJson("Person not found")))(id => {
        HttpResponse.ok.withBody(Json.toJson(repo.get(id)))
      })
  }
}

For more information see the seed projects on the main page of sbt-sam.