Products Routes - Create and Load all Products
Learn how to implement tapir and http4s endpoints for loading and updating products and combining them.
Tapir endpoint for creating a product
Press + to interact
val createProduct: Endpoint[Product, StatusCode, Unit, Nothing] =endpoint.post.in("products").in(jsonBody[Product].description("The product data which should be created.")).errorOut(statusCode).out(statusCode(StatusCodes.NoContent))
As we can see, the endpoint definition for creating a product does not differ from the one that was used to update one. The only difference is that we have a different path here and do not need to extract our Product ID
from the URL path.
http4s implementation of the create product endpoint
Press + to interact
val createRoute: HttpRoutes[F] =ProductsRoutes.createProduct.toRoutes { product =>for {cnt <- repo.saveProduct(product)res = cnt match {case 0 => StatusCodes.InternalServerError.asLeft[Unit]case _ => ().asRight[StatusCode]}} yield res}
The implementation is again pretty simple. In case the saveProduct
function returns a zero, we output a 500 Internal Server Error
because the product has not been saved into the database (Line 6).
Tapir endpoint for loading all products
Finally, we have our streaming endpoint left. Let’s see how we can do this via tapir.
Press + to interact
// Our type is Endpoint[Unit, StatusCode, Stream[F, Byte], Stream[F, Byte]]def getProducts[F[_]] =endpoint.get.in("products").errorOut(statusCode).out(streamBody[Stream[F, Byte]](schemaFor[Byte], tapir.MediaType.Json()))
The first thing we can see is that we used a def
...