/examples/src/main/scala/Greeter1.scala

https://github.com/jtownson/swakka · Scala · 81 lines · 45 code · 15 blank · 21 comment · 0 complexity · 5951084d722b7191afb2aa8202f37d1e MD5 · raw file

  1. /*
  2. * Copyright 2017 Jeremy Townson
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. import akka.actor.ActorSystem
  17. import akka.http.scaladsl.Http
  18. import akka.http.scaladsl.model.HttpMethods.GET
  19. import akka.http.scaladsl.model.HttpResponse
  20. import akka.http.scaladsl.model.StatusCodes.OK
  21. import akka.http.scaladsl.model.headers.RawHeader
  22. import akka.http.scaladsl.server.Directives.complete
  23. import akka.http.scaladsl.server.Route
  24. import akka.stream.ActorMaterializer
  25. import scala.collection.immutable.Seq
  26. // Shows how to create
  27. // an endpoint that accepts a query parameter
  28. // Usage: curl -i http://localhost:8080/greet?name=John
  29. // API model
  30. import net.jtownson.swakka.openapimodel._
  31. // Akka http route generation
  32. import net.jtownson.swakka.coreroutegen._
  33. import net.jtownson.swakka.openapiroutegen._
  34. // Serialization of swagger.json
  35. import net.jtownson.swakka.openapijson._
  36. object Greeter1 extends App {
  37. implicit val system = ActorSystem()
  38. implicit val mat = ActorMaterializer()
  39. implicit val executionContext = system.dispatcher
  40. val corsHeaders = Seq(
  41. RawHeader("Access-Control-Allow-Origin", "*"),
  42. RawHeader("Access-Control-Allow-Methods", "GET"))
  43. val greet: String => Route =
  44. name =>
  45. complete(HttpResponse(OK, corsHeaders, s"Hello $name!"))
  46. val api =
  47. OpenApi(
  48. produces = Some(Seq("text/plain")),
  49. paths =
  50. PathItem(
  51. path = "/greet",
  52. method = GET,
  53. operation = Operation(
  54. parameters = Tuple1(QueryParameter[String]('name)),
  55. responses = ResponseValue[String]("200", "ok"),
  56. endpointImplementation = greet
  57. )
  58. )
  59. )
  60. val route: Route = openApiRoute(api, Some(DocRouteSettings(
  61. corsUseCase = SpecificallyThese(corsHeaders))))
  62. val bindingFuture = Http().bindAndHandle(
  63. route,
  64. "localhost",
  65. 8080)
  66. }