=doc #19840 Introduction docs for HTTP
This commit is contained in:
parent
06b4d54960
commit
61ff9ba9b9
5 changed files with 382 additions and 67 deletions
|
|
@ -8,9 +8,13 @@ import akka.http.scaladsl.marshallers.sprayjson.SprayJsonSupport
|
|||
import akka.http.scaladsl.server.Directives
|
||||
import org.scalatest.{ Matchers, WordSpec }
|
||||
|
||||
import scala.concurrent.Future
|
||||
|
||||
class SprayJsonExampleSpec extends WordSpec with Matchers {
|
||||
|
||||
"spray-json example" in {
|
||||
def compileOnlySpec(body: => Unit) = ()
|
||||
|
||||
"spray-json example" in compileOnlySpec {
|
||||
//#example
|
||||
import spray.json._
|
||||
|
||||
|
|
@ -31,9 +35,7 @@ class SprayJsonExampleSpec extends WordSpec with Matchers {
|
|||
val route =
|
||||
get {
|
||||
pathSingleSlash {
|
||||
complete {
|
||||
Item("thing", 42) // will render as JSON
|
||||
}
|
||||
complete(Item("thing", 42)) // will render as JSON
|
||||
}
|
||||
} ~
|
||||
post {
|
||||
|
|
@ -47,4 +49,63 @@ class SprayJsonExampleSpec extends WordSpec with Matchers {
|
|||
//#
|
||||
}
|
||||
}
|
||||
|
||||
"second-spray-json-example" in compileOnlySpec {
|
||||
//#second-spray-json-example
|
||||
import akka.actor.ActorSystem
|
||||
import akka.stream.ActorMaterializer
|
||||
import akka.Done
|
||||
import akka.http.scaladsl.server.Route
|
||||
import akka.http.scaladsl.server.Directives._
|
||||
import akka.http.scaladsl.model.StatusCodes
|
||||
import akka.http.scaladsl.marshallers.sprayjson.SprayJsonSupport._
|
||||
import spray.json.DefaultJsonProtocol._
|
||||
|
||||
object WebServer {
|
||||
|
||||
// domain model
|
||||
final case class Item(name: String, id: Long)
|
||||
final case class Order(items: List[Item])
|
||||
|
||||
// formats for unmarshalling and marshalling
|
||||
implicit val itemFormat = jsonFormat2(Item)
|
||||
implicit val orderFormat = jsonFormat1(Order)
|
||||
|
||||
// (fake) async database query api
|
||||
def fetchItem(itemId: Long): Future[Option[Item]] = ???
|
||||
def saveOrder(order: Order): Future[Done] = ???
|
||||
|
||||
def main(args: Array[String]) {
|
||||
|
||||
// needed to run the route
|
||||
implicit val system = ActorSystem()
|
||||
implicit val materializer = ActorMaterializer()
|
||||
|
||||
val route: Route =
|
||||
get {
|
||||
pathPrefix("item" / LongNumber) { id =>
|
||||
// there might be no item for a given id
|
||||
val maybeItem: Future[Option[Item]] = fetchItem(id)
|
||||
|
||||
onSuccess(maybeItem) {
|
||||
case Some(item) => complete(item)
|
||||
case None => complete(StatusCodes.NotFound)
|
||||
}
|
||||
}
|
||||
} ~
|
||||
post {
|
||||
path("create-order") {
|
||||
entity(as[Order]) { order =>
|
||||
val saved: Future[Done] = saveOrder(order)
|
||||
onComplete(saved) { done =>
|
||||
complete("order created")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
//#second-spray-json-example
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue