...
Xitcaweb

Building a REST API with Rust and Xitca Framework

PostgreSQL Integration

This guide will walk you through creating a REST API using Rust and the Xitca framework, connecting to a PostgreSQL database. The API will have two endpoints:

  • GET /api/getUserData: Retrieves user data from the users table based on the provided user_id parameter.
  • POST /api/updateUser: Updates user data in the users table based on the provided user_id, fullname, and email parameters.

Prerequisites:

  • Rust installed
  • Basic understanding of Rust programming
  • Familiarity with REST API concepts
  • PostgreSQL database set up

Steps:

  1. Create a Rust project:
   cargo new xitca_api
  1. Install Xitca and dependencies:
   cargo add xitca xitca-postgres --version ^0.4.0
  1. Define data models: Create a models.rs file to define the data structures for users:
   use xitca::serde::{Deserialize, Serialize};

   #[derive(Debug, Deserialize, Serialize)]
   pub struct User {
       user_id: i32,
       fullname: String,
       email: String,
   }
  1. Implement database access (using Xitca’s xitca-postgres extension):
   // Add `sqlx` and `postgres` dependencies to `Cargo.toml`
   cargo add sqlx postgres

   // Create a `db.rs` file for database operations
   use xitca::{
       Body, Context, Request, Response, ServiceExt,
       Router,
       Xitca,
   };
   use crate::models::User;
   use sqlx::{Executor, QueryAs};

   pub async fn get_user_data(ctx: &Context, user_id: i32) -> Result<User, xitca::Error> {
       let row = QueryAs::<User>::query("SELECT * FROM users WHERE user_id = $1", user_id)
           .fetch_one(&ctx.db())
           .await?;
       Ok(row)
   }

   pub async fn update_user(ctx: &Context, user: User) -> Result<(), xitca::Error> {
       sqlx::query("UPDATE users SET fullname = $1, email = $2 WHERE user_id = $3", user.fullname, user.email, user.user_id)
           .execute(&ctx.db())
           .await?;
       Ok(())
   }
  1. Create route handlers: Create a routes.rs file to define the API routes and handlers:
   use xitca::{
       Body, Context, Request, Response, ServiceExt,
       Router,
       Xitca,
   };
   use crate::{db::*, models::User};

   pub async fn get_user_data_handler(ctx: &Context, user_id: i32) -> Response {
       let user = get_user_data(ctx, user_id).await.unwrap_or_else(|_| User { user_id: 0, fullname: "".to_string(), email: "".to_string() });
       Body::json(user).to_response()
   }

   pub async fn update_user_handler(ctx: &Context, mut user: User) -> Response {
       let user_id = user.user_id;
       update_user(ctx, &user).await.unwrap();
       Body::json(user).to_response()
   }
  1. Register routes and start the server: Create a main.rs file to register routes and start the server: “`rust
    use xitca::{
    Body, Context, Request, Response, ServiceExt,
    Router,
    Xitca,
    };
    use crate::routes::*; pub async fn run_server() {
    let db = sqlx::connect(“postgres://user:password@localhost:5432/db”)
    .await
    .unwrap(); let router = Router::new()
    .get(“/api/getUserData/{user_id}”, get_user_data_handler)
    .post(“/api/updateUser”, update_user_handler); let xitca = Xitca::new(router);
    xitca.run

MySQL Integration

This guide will walk you through creating a REST API using Rust and the Xitca framework, connecting to a MySQL database. The API will have two endpoints:

  • GET /api/getUserData: Retrieves user data from the users table based on the provided user_id parameter.
  • POST /api/updateUser: Updates user data in the users table based on the provided user_id, fullname, and email parameters.

Prerequisites:

  • Rust installed
  • Basic understanding of Rust programming
  • Familiarity with REST API concepts
  • MySQL database set up

Steps:

  1. Create a Rust project:
   cargo new xitca_api
  1. Install Xitca and dependencies:
   cargo add xitca xitca-mysql --version ^0.4.0
  1. Define data models: Create a models.rs file to define the data structures for users:
   use xitca::serde::{Deserialize, Serialize};

   #[derive(Debug, Deserialize, Serialize)]
   pub struct User {
       user_id: i32,
       fullname: String,
       email: String,
   }
  1. Implement database access (using Xitca’s xitca-mysql extension):
   // Add `mysql` dependency to `Cargo.toml`
   cargo add mysql

   // Create a `db.rs` file for database operations
   use xitca::{
       Body, Context, Request, Response, ServiceExt,
       Router,
       Xitca,
   };
   use crate::models::User;
   use mysql::{Opts, Pool};

   pub async fn get_user_data(ctx: &Context, user_id: i32) -> Result<User, xitca::Error> {
       let mut conn = ctx.db().get_conn().await.unwrap();
       let row = conn.query_row::<_, User>("SELECT * FROM users WHERE user_id = ?", user_id).await.unwrap();
       Some(row)
   }

   pub async fn update_user(ctx: &Context, user: User) -> Result<(), xitca::Error> {
       let mut conn = ctx.db().get_conn().await.unwrap();
       conn.execute("UPDATE users SET fullname = ?, email = ? WHERE user_id = ?", user.fullname, user.email, user.user_id).await.unwrap();
       Ok(())
   }
  1. Create route handlers: Create a routes.rs file to define the API routes and handlers:
   use xitca::{
       Body, Context, Request, Response, ServiceExt,
       Router,
       Xitca,
   };
   use crate::{db::*, models::User};

   pub async fn get_user_data_handler(ctx: &Context, user_id: i32) -> Response {
       let user = get_user_data(ctx, user_id).await.unwrap_or_else(|_| User { user_id: 0, fullname: "".to_string(), email: "".to_string() });
       Body::json(user).to_response()
   }

   pub async fn update_user_handler(ctx: &Context, mut user: User) -> Response {
       let user_id = user.user_id;
       update_user(ctx, &user).await.unwrap();
       Body::json(user).to_response()
   }
  1. Register routes and start the server: Create a main.rs file to register routes and start the server: “`rust
    use xitca::{
    Body, Context, Request, Response, ServiceExt,
    Router,
    Xitca,
    };
    use crate::routes::*; pub async fn run_server() {
    let pool = Pool::connect(“mysql://user:password@localhost:3306/db”)
    .await
    .unwrap(); let router = Router::new()
    .get(“/api/getUserData/{user_id}”, get_user_data_handler)
    .post(“/api/updateUser”, update_user_handler); let xitca = Xitca::new(router);
    xitca.run(“0

Leave a Reply

Your email address will not be published. Required fields are marked *