DEV Community

Sivakumar
Sivakumar

Posted on

REST API Implementation in Rust

In this blog post, let us see how to build a simple REST API in Rust.

Pre-requisites
  • Cargo
  • PostgreSQL
  • Environment variable DATABASE_URL configured with postgres database URL
Crates used in this example project

Following crates are used in this project

  • actix_rt: Tokio-based single threaded async runtime for the Actix ecosystem
  • actix_web: Actix Web is a powerful, pragmatic, and extremely fast web framework for Rust
  • serde: A generic serialization/deserialization framework
  • serde_json: A JSON serialization file format
  • chrono: Data and time library
  • uuid: A library to generate and parse UUID
  • env_logger: A logging implementation for ==log== which is configured via an environment variable
  • diesel: A safe, extensible ORM framework and Query builder
  • r2d2: A generic connection pool
  • r2d2-diesel: r2d2 support for Diesel ORM
Setup
PostgreSQL Table schema

I am creating below tables in test schema in PostgreSQL DB. In case if you intend to use different schema, please use that as well. Make sure to specify correct schema in DATABASE_URL environment variable as well.

Ex:

set DATABASE_URL=postgres://postgres:postgres@localhost:5432/testdb?options=-c%20search_path%3Dtest
Enter fullscreen mode Exit fullscreen mode

I am going to create 2 tables. One for storing Tweets and another one is to keep tracking the likes for each Tweet. Create table scripts for the 2 tables as below:

create table test.tweets (
id uuid not null primary key, 
created_at timestamp not null, 
message varchar(500)
);

create table test.likes (
id uuid not null primary key, 
created_at timestamp not null, 
tweet_id uuid not null references test.tweets(id));
Enter fullscreen mode Exit fullscreen mode
Checkout the sample project

You can do git clone this project to your local machine

git clone https://github.com/sivakumar-sivaprakasam/simple_twitter_rest_api.git
Enter fullscreen mode Exit fullscreen mode
Launch the application

Once the pre-requisites are well configured, please run cargo run to launch the application. You can use below CURL commands to test the application

Post a tweet

curl -X POST -d "{\"message\": \"This is a tweet\"}" -H "Content-type: application/json" http://localhost:9090/tweets
Enter fullscreen mode Exit fullscreen mode

Retrieve all tweets

curl http://localhost:9090/tweets
Enter fullscreen mode Exit fullscreen mode

Get a specific tweet

curl http://localhost:9090/tweets/{id}
Enter fullscreen mode Exit fullscreen mode

Like a tweet

curl -X POST http://localhost:9090/tweets/{id}/likes
Enter fullscreen mode Exit fullscreen mode

Unlike a tweet

curl -X DELETE http://localhost:9090/tweets/{id}/likes
Enter fullscreen mode Exit fullscreen mode

Delete a tweet

curl -X DELETE http://localhost:9090/tweets/{id}
Enter fullscreen mode Exit fullscreen mode

Please feel free to share your comments.

Happy exploring rust !!!

Top comments (0)