[Part 6] API Handlers

[Part 6] API Handlers

Jan 9, 2022ยท

2 min read

Play this article

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:


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

use crate::AppState;

async fn get_todos(state: web::Data<AppState>) -> ActixResult<impl Responder, ActixError> {
    let todos = state.todo_repository.get_todos().await;

pub fn todos_handler() -> Scope {

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.


Nothing special

pub use super::todos::todos_handler;


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;


pub fn init(cfg: &mut web::ServiceConfig) {

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


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!