Omprakash Sridharan
Omprakash Sridharan

Follow

Omprakash Sridharan

Follow
[Part 6] API Handlers

[Part 6] API Handlers

Omprakash Sridharan's photo
Omprakash Sridharan
ยทJan 9, 2022ยท

2 min read

Table of contents

  • todos.rs
  • prelude.rs
  • mod.rs
  • The wait is over ๐Ÿ˜
  • Adding some test data

Let's create the final module of this series, the handler. Create a folder handler under src and it was have... you guessed it ! 3 files:

todos.rs

use actix_web::{get, web, Error as ActixError, Responder, Result as ActixResult, Scope};

use crate::AppState;

#[get("/")]
async fn get_todos(state: web::Data<AppState>) -> ActixResult<impl Responder, ActixError> {
    let todos = state.todo_repository.get_todos().await;
    Ok(web::Json(todos))
}

pub fn todos_handler() -> Scope {
    web::scope("/todos").service(get_todos)
}

We are importing stuff from actix to annotate types in the first line. We then have our API handler which is our get_todos function. Notice that it is annotated with #[get("/")] which denotes that this is a get method at path "/". Inside we use the state that we configured in main and call the get_todos method in todo_repository. We then return the response as a web::Json format. (Refer back to the sea-orm-cli command where we added the with-serde flag which makes the serialisation of rust structs to JSON automatically ๐Ÿช„)

At last we create a public function todos_handler which creates an Actix scope which is nothing but a collection of sub handlers or sub scopes under a prefix. This means that now our API will be available under localhost:8000/todos path. Don't run it yet because we now have to link the handler to the main.

prelude.rs

Nothing special

pub use super::todos::todos_handler;

mod.rs

Easy !

pub mod prelude;
mod todos;

The wait is over ๐Ÿ˜

In main.rs, import the todos_handler at the top and inside the init function register as shown.

use handler::prelude::todos_handler;

// ALL CODE

pub fn init(cfg: &mut web::ServiceConfig) {
    cfg.service(todos_handler());
}

Finally run cargo check once to make sure everything is good and run the below command

cargo run

If everything went according to plan, we would have the server up and running on the specified host and port in .env

DATABASE_URL=mysql://<username>:<password>@localhost/rust_todo_actix_seaorm
HOST=127.0.0.1
PORT=8000

Adding some test data

Run the below SQL command to add some data to your database.

insert into todos (todo_id,todo_name,todo_description) values (1,"test","test description");

insert into todos (todo_id,todo_name,todo_description) values (2,"test2","test description 2");

Visit localhost:8000/todos in your browser and see the data returned ๐Ÿฅบ

Screenshot 2022-01-09 at 4.50.00 PM.png

Did you find this article valuable?

Support Omprakash Sridharan by becoming a sponsor. Any amount is appreciated!

Learn more about Hashnode Sponsors
ย 
Share this