0

REST API with Rust, Actix-web, and PostgreSQL – Part 3

We had an overview of the project structure. This post shows the codes of the files mentioned in the previous post.

main.rs

The main.rs  files has the following main()  function codes.

Each service has a unique resource. Each resource has routes. For instance, the resource /persons/{person_id}  allows for HTTP GET , HTTP DELETE , and HTTP PUT  methods. Each of this method triggers a handler function.

Handler Functions

These are “web controller”-level functions.

get_person_list

This function retrieves all the person records from the database through the person  module.

get_person

This function retrieves a particular person record from the database by person_id .

create_person

This function creates a person record in the database.

update_person

This function updates a person’s name in the database.

delete_person

This function deletes a person record in the database by person_id .

Person Module

common.rs

This file contains the structs for our codes.

The struct Person  also represents a person record in the database. The others are used to automatically map the JSON s from incoming requests to their instances.

mod.rs

The first three lines make the common mod  available and uses the extern  and use  statements for postgres  crate.

The connection string for PostgreSQL are stored in a global static variable.

The rest of the codes are functions that directly access the database.

get_person_all

This function retrieves all person records from the database and put them in a Vec<common::Person>  instance.

get_person_by_id

This function retrieves a person record by person_id . The record is put in a Vec<common::Person>  instance as well.

create_person

This function creates a person record in the database.

delete_person

This function deletes a person record in the database by person_id .

update_person

This function updates a person name in the database by person_id .

Karl San Gabriel

Karl San Gabriel

Professional Software Developer