Skip to content

Commit 746ad5f

Browse files
committed
Example: respond with 404 if None returned from server logic
1 parent 29bfe9d commit 746ad5f

File tree

1 file changed

+19
-2
lines changed

1 file changed

+19
-2
lines changed

examples/src/main/scala/sttp/tapir/examples/booksExample.scala

Lines changed: 19 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@
1111

1212
package sttp.tapir.examples
1313

14+
import sttp.model.StatusCode
1415
import sttp.tapir.generic.auto.*
1516

1617
@main def booksExample(): Unit =
@@ -56,6 +57,16 @@ import sttp.tapir.generic.auto.*
5657
val booksListingByGenre: PublicEndpoint[BooksQuery, String, Vector[Book], Any] = baseEndpoint.get
5758
.in(("list" / path[String]("genre").map(Option(_))(_.get)).and(limitParameter).mapTo[BooksQuery])
5859
.out(jsonBody[Vector[Book]])
60+
61+
// Optional value from serverLogic, responding with 404 when None
62+
val singleBook = baseEndpoint.get
63+
.in("book" / query[String]("title"))
64+
.out(oneOf(
65+
oneOfVariantExactMatcher(StatusCode.NotFound, jsonBody[Option[Book]])(None),
66+
oneOfVariantValueMatcher(StatusCode.Ok, jsonBody[Option[Book]]) {
67+
case Some(book) => true
68+
}
69+
))
5970
end Endpoints
6071

6172
//
@@ -123,12 +134,18 @@ import sttp.tapir.generic.auto.*
123134
Right[String, Vector[Book]](Library.getBooks(query))
124135
}
125136

137+
def singleBookLogic(title: String): Future[Either[String, Option[Book]]] =
138+
Future {
139+
Right(Library.Books.get().find(_.title == title))
140+
}
141+
126142
// interpreting the endpoint description and converting it to an pekko-http route, providing the logic which
127143
// should be run when the endpoint is invoked.
128144
List(
129145
addBook.serverLogic(bookAddLogic.tupled),
130146
booksListing.serverLogic(bookListingLogic),
131-
booksListingByGenre.serverLogic(bookListingByGenreLogic)
147+
booksListingByGenre.serverLogic(bookListingByGenreLogic),
148+
singleBook.serverLogic(singleBookLogic)
132149
)
133150
end booksServerEndpoints
134151

@@ -137,7 +154,7 @@ import sttp.tapir.generic.auto.*
137154

138155
// interpreting the endpoint descriptions as yaml openapi documentation
139156
// exposing the docs using SwaggerUI endpoints, interpreted as an pekko-http route
140-
SwaggerInterpreter().fromEndpoints(List(addBook, booksListing, booksListingByGenre), "The Tapir Library", "1.0")
157+
SwaggerInterpreter().fromEndpoints(List(addBook, booksListing, booksListingByGenre, singleBook), "The Tapir Library", "1.0")
141158
end swaggerUIServerEndpoints
142159

143160
def startServer(serverEndpoints: List[ServerEndpoint[Any, Future]]): Unit =

0 commit comments

Comments
 (0)