In this article I will be going to explore Rocket.rs starting with the basics
What is Rocket.rs
A web framework for Rust gear Rust that makes it simple to write fast, type-safe, secure web applications with incredible usability, productivity and performance
Requirements
Lets start by setting up rust
rustup default stable
Lets create the new project
cargo new hello-rocket --bin cd hello-rocket
Now, add Rocket as a dependency in your Cargo.toml
[dependencies] rocket = "0.5.0"
Change the src/main.rs file with the following code:
Now that we done the Hello World application lets spike a bit and create a API based on the following article
This article will teach you how to build a simple CRUD API with Rust using the Rocket framework. We’ll create a RESTful API that runs on a Rocket HTTP server and persists data in an in-memory database. (Check the original article if you want to deep dive)
Setup
Lets start by instantiating a rust project to create our API
mkdir simple-api-rocket cd simple-api-rocket cargo init
For this exercise we will use a in-memory database available to all the route handlers, we’ll use Rust’s smart pointer called Arc along with the Mutex.
Create the Model
Create the file model.rs file and add the following code:
use chrono::prelude::*; use serde::{Deserialize, Serialize}; use std::sync::{Arc, Mutex};
This code created a Todo struct and added Serde’s macros on top of it.
The Deserialize and Serialize macros will allow us to convert the struct to and from JSON
Create the API Response Structs
Here, let’s create structs that implement the [derive(Serialize)] macro to enable us to convert structs into JSON objects before returning them to the client.
So, create a response.rs file in the src directory and add the following structs:
[get("/healthchecker")] – This route will return a simple health checker JSON object.
[get("/todos?<page>&<limit>")] – This route will return a selected or paginated list of Todo items.
[post("/todos", data = "<body>")] – This route will add a new Todo item to the data store.
[get("/todos/<id>")] – This route will retrieve a single Todo item from the in-memory database and return it to the client.
[patch("/todos/<id>", data = "<body>")] – This route will edit the fields of a Todo item in the data store.
[delete("/todos/<id>")] – This route will delete a Todo item from the in-memory database.
First things first, create a handler.rs file in the src folder and add the following crates and dependencies.
use crate::{ model::{AppState, Todo, UpdateTodoSchema}, response::{GenericResponse, SingleTodoResponse, TodoData, TodoListResponse}, }; use chrono::prelude::*; use rocket::{ delete, get, http::Status, patch, post, response::status::Custom, serde::json::Json, State, }; use uuid::Uuid;
#[get("/healthchecker")] pubasyncfnhealth_checker_handler() ->Result<Json<GenericResponse>, Status> { const MESSAGE: &str = "Build Simple CRUD API with Rust and Rocket";
You can also use the following json file to test with Postman
Make sure to check the original article which has more detailed information on the this setup
Now we just need some React FrontEnd Application to interact with this service.
Create FrontEnd Application
Now similar to my previous post related with Strapi lets create a frontend application with react.
On a different folder run the following command (Require bun.sh )
bunx create-react-app todo-frontend
Next create the following two files for the environment variables:
.env.development
REACT_APP_BACKEND=http://localhost:1337/
.env.production
REACT_APP_BACKEND=/
You can run the frontend application with the following command
bun run start
I’m not an expert in Frontend development and I did manage to get the create operation working, but the listing however didn’t populate although I could see on the console the data was refreshed and as the article is already long, I decided to stop here.
If you manage to get the react component working let me know so that I can update the article.
Cargo Watch
In Rust we have a library called cargo-watch which watches the source code for changes and hot-reloads the server when required files change. Lets install it
cargo install cargo-watch
With that out of the way, run this command to start the Rocket HTTP server and restart the server when any file in the src directory changes.
cargo watch -q -c -w src/ -x run
Conclusion
Rust is gaining quite a lot popularity, implementing APIs with Rocket seems fast. This mix of React and Rust in the near future should be mixture that you would will see more.
The performance os Rust allied to the flexibility from the frontend component is something that I need to explore more.