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 ( ...
Access this course and 1400+ top-rated courses and projects.