PostgreSQL Integration
This guide will walk you through creating a REST API using Rust and the Ntex framework, connecting to a PostgreSQL database. The API will have two endpoints:
GET /api/getUserData
: Retrieves user data from theusers
table based on the provideduser_id
parameter.POST /api/updateUser
: Updates user data in theusers
table based on the provideduser_id
,fullname
, andemail
parameters.
Prerequisites:
- Rust installed
- Basic understanding of Rust programming
- Familiarity with REST API concepts
- PostgreSQL database set up
Steps:
- Create a Rust project:
cargo new ntex_api
- Install Ntex and dependencies:
cargo add ntex ntex-postgres --version ^0.10
- Define data models: Create a
models.rs
file to define the data structures for users:
use ntex::serde::Serialize;
#[derive(Debug, Serialize)]
pub struct User {
user_id: i32,
fullname: String,
email: String,
}
- Implement database access (using Ntex’s
ntex-postgres
extension):
// Add `sqlx` and `postgres` dependencies to `Cargo.toml`
cargo add sqlx postgres
// Create a `db.rs` file for database operations
use ntex::{
web::{self, types::Path},
DatabaseExt,
};
use crate::models::User;
use sqlx::{Connection, Pool};
pub async fn get_user_data(pool: &Pool<Postgres>, user_id: i32) -> Option<User> {
sqlx::query_as!(User, "SELECT * FROM users WHERE user_id = $1", user_id)
.fetch_optional(pool)
.await
.unwrap()
}
pub async fn update_user(pool: &Pool<Postgres>, user: User) {
sqlx::query!("UPDATE users SET fullname = $1, email = $2 WHERE user_id = $3", user.fullname, user.email, user.user_id)
.execute(pool)
.await
.unwrap();
}
- Create route handlers: Create a
routes.rs
file to define the API routes and handlers:
use ntex::{
web::{self, types::Path},
DatabaseExt,
Json,
};
use crate::{db::*, models::User};
#[get("/api/getUserData/{user_id}")]
async fn get_user_data_handler(Path(user_id): Path<i32>, pool: web::types::Context<Pool<Postgres>>) -> Json<Option<User>> {
let user = get_user_data(&pool, user_id).await;
Json(user)
}
#[post("/api/updateUser")]
async fn update_user_handler(Json(user): Json<User>, pool: web::types::Context<Pool<Postgres>>) {
update_user(&pool, user).await;
Json(user)
}
- Register routes and start the server: Create a
main.rs
file to register routes and start the server: “`rust
use ntex::{
web::{self, types::Path},
DatabaseExt,
Server,
service::{
create_router,
http_router,
middleware::CorsConfig,
TypedBody,
},
};
use crate::routes::*; pub async fn run_server() {
let pool = Pool::connect(“postgres://user:password@localhost:5432/db”)
.await
.unwrap(); let app = http_router(
[
get_user_data_handler,
update_user_handler,
],
Extension(pool),
)
.with_middleware(Cors::new().allow_origin(“*”)); let addr = std::net::SocketAddr::from_str(“0.0.0.0:8080”).unwrap();
println!(“Starting server on {}”, addr);
MySQL Integration
This guide will walk you through creating a REST API using Rust and the Ntex framework, connecting to a MySQL database. The API will have two endpoints:
GET /api/getUserData
: Retrieves user data from theusers
table based on the provideduser_id
parameter.POST /api/updateUser
: Updates user data in theusers
table based on the provideduser_id
,fullname
, andemail
parameters.
Prerequisites:
- Rust installed
- Basic understanding of Rust programming
- Familiarity with REST API concepts
- MySQL database set up
Steps:
- Create a Rust project:
cargo new ntex_api
- Install Ntex and dependencies:
cargo add ntex ntex-mysql --version ^0.10
- Define data models: Create a
models.rs
file to define the data structures for users:
use ntex::serde::Serialize;
#[derive(Debug, Serialize)]
pub struct User {
user_id: i32,
fullname: String,
email: String,
}
- Implement database access (using Ntex’s
ntex-mysql
extension):
// Add `mysql` dependency to `Cargo.toml`
cargo add mysql
// Create a `db.rs` file for database operations
use ntex::{
web::{self, types::Path},
DatabaseExt,
};
use crate::models::User;
use mysql::{Opts, Pool};
pub async fn get_user_data(pool: &Pool, user_id: i32) -> Option<User> {
let mut conn = pool.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(pool: &Pool, user: User) {
let mut conn = pool.get_conn().await.unwrap();
conn.execute("UPDATE users SET fullname = ?, email = ? WHERE user_id = ?", user.fullname, user.email, user.user_id).await.unwrap();
}
- Create route handlers: Create a
routes.rs
file to define the API routes and handlers:
use ntex::{
web::{self, types::Path},
DatabaseExt,
Json,
};
use crate::{db::*, models::User};
#[get("/api/getUserData/{user_id}")]
async fn get_user_data_handler(Path(user_id): Path<i32>, pool: web::types::Context<Pool>) -> Json<Option<User>> {
let user = get_user_data(&pool, user_id).await;
Json(user)
}
#[post("/api/updateUser")]
async fn update_user_handler(Json(user): Json<User>, pool: web::types::Context<Pool>) {
update_user(&pool, user).await;
Json(user)
}
- Register routes and start the server: Create a
main.rs
file to register routes and start the server: “`rust
use ntex::{
web::{self, types::Path},
DatabaseExt,
Server,
service::{
create_router,
http_router,
middleware::CorsConfig,
TypedBody,
},
};
use crate::routes::*; pub async fn run_server() {
let pool = Pool::connect(“mysql://user:password@localhost:3306/db”)
.await
.unwrap(); let app = http_router(
[
get_user_data_handler,
update_user_handler,
],
Extension(pool),
)
.with_middleware(Cors::new().allow_origin(“*”)); let addr = std::net::SocketAddr::from_str(“0.0.0.0:8080”).unwrap();
println!(“Starting server on {}”, addr);
Server::bind_and_run(addr, app
Leave a Reply