Search⌘ K
AI Features

Products Routes - Create and Load all Products

Explore how to create and load all products using Tapir endpoints and http4s in Scala. Understand designing routes for product creation and streaming, handling HTTP errors, converting streams for JSON output, and running tests with a preconfigured environment.

Tapir endpoint for creating a product

Scala
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

Scala
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.

Scala
// 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 ...