11
11
12
12
package sttp .tapir .examples
13
13
14
+ import sttp .model .StatusCode
14
15
import sttp .tapir .generic .auto .*
15
16
16
17
@ main def booksExample (): Unit =
@@ -56,6 +57,16 @@ import sttp.tapir.generic.auto.*
56
57
val booksListingByGenre : PublicEndpoint [BooksQuery , String , Vector [Book ], Any ] = baseEndpoint.get
57
58
.in((" list" / path[String ](" genre" ).map(Option (_))(_.get)).and(limitParameter).mapTo[BooksQuery ])
58
59
.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
+ ))
59
70
end Endpoints
60
71
61
72
//
@@ -123,12 +134,18 @@ import sttp.tapir.generic.auto.*
123
134
Right [String , Vector [Book ]](Library .getBooks(query))
124
135
}
125
136
137
+ def singleBookLogic (title : String ): Future [Either [String , Option [Book ]]] =
138
+ Future {
139
+ Right (Library .Books .get().find(_.title == title))
140
+ }
141
+
126
142
// interpreting the endpoint description and converting it to an pekko-http route, providing the logic which
127
143
// should be run when the endpoint is invoked.
128
144
List (
129
145
addBook.serverLogic(bookAddLogic.tupled),
130
146
booksListing.serverLogic(bookListingLogic),
131
- booksListingByGenre.serverLogic(bookListingByGenreLogic)
147
+ booksListingByGenre.serverLogic(bookListingByGenreLogic),
148
+ singleBook.serverLogic(singleBookLogic)
132
149
)
133
150
end booksServerEndpoints
134
151
@@ -137,7 +154,7 @@ import sttp.tapir.generic.auto.*
137
154
138
155
// interpreting the endpoint descriptions as yaml openapi documentation
139
156
// 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" )
141
158
end swaggerUIServerEndpoints
142
159
143
160
def startServer (serverEndpoints : List [ServerEndpoint [Any , Future ]]): Unit =
0 commit comments