CRUD operations in RUST

Reading Time: 3 minutes

Hello Readers! In this blog, we will discuss HTTP Methods(CRUD operations). REST APIs(Representational State Transfer Application Programming Interface) enables you to develop all kinds of web applications having all possible CRUD (create, retrieve, update, delete) operations. So let’s have a basic idea of what CRUD stands for and what all HTTP methods are used in correspondence to CRUD operations.

C: It stands for Create, and is responsible for the POST HTTP Method.

R: It stands for Read, and it is responsible for GET HTTP Method.

U: It stands for Update, and it is responsible for PUT and PATCH HTTP Methods.

D: It stands for Delete, and it is responsible for the DELETE HTTP Method.

RUST frameworks for Rest APIs

The language shares many similarities with C and C++, while offering essential syntax modifications of its own. Accordingly, developers praise Rust for its open-source development and performance. This makes it a prime candidate for API creation. Below, we’ll review three superb frameworks for building APIs using Rust.

The 3 basic frameworks for creating REST APIs in RUST are:

  1. Rocket
  2. Actix-web
  3. Tower Web

ROCKET

  • It is a web framework for Rust that makes it simple to write fast, secure web applications.
  • Rocket is built for speed with fast templating and incoming/outgoing data streaming, which is file-size agnostic.
  • The request-response process occurs in only three steps, emphasizing sound validation, customized error reporting, and simple arbitrary-handler functions.
  • JSON support is baked in via Serialize or Deserialize. Using the FromData trait ensures easy value creation by type.
  • It can be tricky keeping all components of Rocket properly updated over time
  • Ongoing changes in Rust nightly can cause unpredictable, breaking changes
  • Rocket has depended on nightly Rust and doesn’t run on stable versions of the Rust compiler. This feature is pending, however – v0.5 is in development, and will add support for Rust stable.

Actix-web

  • It is usable and lightweight. Initially released in October of 2017 and maintained by Nikolay Kim, Actix-web supports the Actix actor framework.
  • Supports both HTTP/1.x and HTTP 2.0 protocols
  • It supports data streaming while adding pipelining support, cutting down on response times by packaging requests on a single TCP connection.
  • Actix-web can serve both static and dynamic assets via OpenSSL or rustls
  • Heavy reliance on unsafe code instances to allow for improved performance, though this has been mitigated in recent versions

Tower Web

  • With a focus on simplifying API development via boilerplate removal, Tower Web is a lean-yet-powerful Rust framework.
  • t’s built upon Tower, a complimentary library containing useful network components. Much like Actix-web leans on Actix, Tower Web does the same with Tower. It’s also built upon Tokio and Hyper – a non-blocking I/O platform and HTTP client, respectively.
  • Complete asynchronicity allows multiple processes to run simultaneously, eliminating bottlenecks
  • HTTP is separated from your application’s logic, erasing the need for boilerplate and cutting down on cruft
  • Tower Web is compatible with Rust stable, meaning ongoing changes to nightly won’t break your build
  • Since Tower Web is newer, developers are still waiting for additional components, such as middleware, to be written
  • Documentation could be more comprehensive

Basic Example Of REST API in RUST using Actix-Web

  • We assume that you have installed Rust already. If not, check here.
  • You need to know a little bit about Cargo. We’re going to use cargo because it’s the official dependency management solution for Rust language.

First, you need to create a new Rust pacakge using cargo’s new command

cargo new rest-api

Now if you navigate to rest-api directory you should see this structure.

rest-api
---- src
---- ---- main.rs
---- .gitignore
---- Cargo.lock
---- Cargo.toml

In this step, you have to add dependencies in Cargo.toml.

[dependencies]
dotenv = "0.15.0"
diesel = { version = "1.4.5", features = ["sqlite"] }
actix-web = "3.3.2"
mime = "0.3.0"
serde = { version = "1.0", features = ["derive"] }

Now write the following code

use actix_web::{get, App, HttpResponse, HttpServer};
use mime::APPLICATION_JSON;
use serde::Serialize;

#[derive(Serialize)]
struct User {
    username: String
}

#[get("/users")]
async fn users() -> HttpResponse {
    HttpResponse::Ok()
        .content_type(APPLICATION_JSON.to_string())
        .json(User {username: String::from("Ayushi")})
}

#[actix_web::main]
async fn main() -> std::io::Result<()> {
    HttpServer::new(||
        App::new().service(users)
    )
    .bind("127.0.0.1:8080")?
    .run()
    .await
}

Use cargo run to run the dummy REST API and test it using curl

curl --request GET --url http://127.0.0.1:8080/user

The output will be a json

{"username":"Ayushi"}

So this was a simple example of Rest Api using Actix-Web. Please stay connected for more such blogs.


If you want to read more content like this?  Subscribe to Rust Times Newsletter and receive insights and latest updates, bi-weekly, straight into your inbox. Subscribe to Rust Times Newsletter: https://bit.ly/2Vdlld7.


Knoldus-blog-footer-image

Written by 

Ayushi is a Software Developer having more than 1.5 year of experience in RUST. Her practice area is Rust and Go. She loves to solve daily coding challenges.