After we defined our API we have to derive the endpoint/set of endpoints we can mount and serve to the world.
val Api =
(api(Get[Json, User], Root / "user" / Segment[String]("name"))) :|:
(apiWithBody(Put[Json, User], ReqBody[Json, User], Root / "user"))
import typedapi.server._
final case class User(name: String)
// implicit encoders and decoders
val endpoints = deriveAll[IO](Api).from(
name => // retrieve and return user
user => // store user
)
deriveAll[IO](Api).from(
name =>
val user: User = ???
success(user) // creates a 200
...
}
or
deriveAll[IO](Api).from(
name =>
val user: User = ???
successWith(StatusCodes.Ok)(user) // set code
...
}
deriveAll[IO](Api).from(
name =>
val user: Option[User] = ???
user.fold(errorWith(StatusCodes.NotFound, s"no user $id")(user => success(user))
...
}
If you want to use http4s as your server backend you have to add the following code:
import typedapi.server.http4s._
import org.http4s.server.blaze.BlazeBuilder
val sm = ServerManager(BlazeBuilder[IO], "http://my-host", myPort)
If you want to use akka-http as your server backend you have to add the following code:
implicit val timeout = 5.second
implicit val system = ActorSystem("akka-http-server")
implicit val mat = ActorMaterializer()
import system.dispatcher
val sm = ServerManager(Http(), "http://my-host", myPort)
Now we can mount endpoints
and serve to to the world:
val server = mount(sm, endpoints)
server.unsafeRunSync()
Make sure you have the proper encoders and decoders in place.