Create Endpoint
Understand how to create and manage a backend endpoint in Rust to receive JSON data, organize database-related code into modules, and test endpoints to ensure functionality and database integrity. This lesson helps you develop practical skills in handling web parameters and Rust code structure for efficient web development.
We'll cover the following...
Creates the handler
In this lesson, we need an endpoint that receives the parameters through the webserver.
We need to make our create_product function public. To do so, we add the pub keyword at the beginning to change the corresponding line.
We also need to add derive instructions to NewProduct and NewCompleteProduct.
We’re now ready to add our new handler. This will capture a JSON form of a NewCompleteProduct object and add it as a parameter to create_product.
Rust organizes code through modules, so we can move all our code to handle database operations to a file called product.rs. We can then use the mod keyword to load that file.
The create_product function requires a product object. However, we have a web::Json object.
In order to obtain our product, we can try to dereference it by using a * before product. However, it won’t work because a move occurs.
We have two alternatives. We can either transform the parameter to a reference in the create_product function or clone the product. It’s safe to clone the product in this case because the object won’t be that big. However, we can transform the parameter to a reference as an alternative to cloning, if we need a performance improvement.
Testing
Now, we need to test our endpoint.
In the above code, we use the function begin_test_transaction to make sure we didn’t commit to the database and to keep it clean.
Testing makes sure we obtain a successful status and the code works as expected.