Rust使用Actix-web和SeaORM库开发WebAPI通过Swagger UI查看接口文档

news/2024/11/13 5:32:45/
webkit-tap-highlight-color: rgba(0, 0, 0, 0);">

本文将介绍Rust语言使用Actix-web和SeaORM库,数据库使用PostgreSQL,开发增删改查项目,同时可以通过Swagger UI查看接口文档和查看标准Rust文档

开始项目

首先创建新项目,名称为rusty_crab_api

cargo new rusty_crab_api

Cargo.toml

[dependencies]
sea-orm = { version = "1.0.0-rc.5", features = [ "sqlx-postgres", "runtime-tokio-native-tls", "macros" ] }
tokio = { version = "1.35.1", features = ["full"] }
chrono = "0.4.33"
actix-web = "4.4.0"
serde = { version = "1.0", features = ["derive"] }
utoipa = { version = "4", features = ["actix_extras"] }
utoipa-swagger-ui = { version = "4", features = ["actix-web"] }
serde_json = "1.0"

使用SeaORM作为ORM工具,它提供了sea-orm-cli​工具,方便生成entity

PostgreSQL创建数据库

CREATE TABLE "user" (id SERIAL PRIMARY KEY,username VARCHAR(32) NOT NULL,birthday TIMESTAMP,sex VARCHAR(10),address VARCHAR(256)
);COMMENT ON COLUMN "user".username IS '用户名称';
COMMENT ON COLUMN "user".birthday IS '生日';
COMMENT ON COLUMN "user".sex IS '性别';
COMMENT ON COLUMN "user".address IS '地址';

安装sea-orm-cli

cargo install sea-orm-cli

生成entity

sea-orm-cli generate entity -u postgres://[用户名]:[密码]@[IP]:[PORT]/[数据库] -o src/entity

自动帮我们生成src./entity/user.rs文件

rust">#[derive(Clone, Debug, PartialEq, DeriveEntityModel, Eq, Serialize, Deserialize)]
#[sea_orm(table_name = "user")]
pub struct Model {#[sea_orm(primary_key)]pub id: i32,pub username: String,pub birthday: Option<DateTime>,pub sex: Option<String>,pub address: Option<String>,
}#[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]
pub enum Relation {}impl ActiveModelBehavior for ActiveModel {}

接下来编写接口函数,新建src/handlers/user.rs,编写用户表的增删改查代码,同时在代码文件中编写说明文档,提供给Rust标准文档和Swagger UI使用

rust">/// 表示创建新用户的请求体结构
#[derive(Debug, Deserialize, ToSchema)]
#[schema(example = json!({"username": "johndoe","birthday": "2023-09-09T15:53:00","sex": "male","address": "123 Main St, Anytown, USA"
}))]
pub struct CreateUser {/// 用户名  pub username: String,/// 生日(可选)#[schema(value_type = String)]pub birthday: Option<DateTime>,/// 性别(可选)pub sex: Option<String>,/// 地址(可选)pub address: Option<String>,
}
/// 创建新用户
///
/// # 请求体
///
/// 需要一个JSON对象,包含以下字段:
/// - `username`: 字符串,用户名(必填)
/// - `birthday`: ISO 8601格式的日期时间字符串,用户生日(可选)
/// - `sex`: 字符串,用户性别(可选)
/// - `address`: 字符串,用户地址(可选)
///
/// # 响应
///
/// - 成功:返回状态码200和新创建的用户JSON对象
/// - 失败:返回状态码500
///
/// # 示例
///
/// ‍‍```
/// POST /users
/// Content-Type: application/json
///
/// {
///     "username": "johndoe",
///     "birthday": "1990-01-01T00:00:00",
///     "sex": "M",
///     "address": "123 Main St, Anytown, USA"
/// }
/// ‍‍```
#[utoipa::path(post,path = "/api/users",request_body = CreateUser,responses((status = 200, description = "User created successfully", body = Model),(status = 500, description = "Internal server error"))
)]
pub async fn create_user(db: web::Data<sea_orm::DatabaseConnection>,user_data: web::Json<CreateUser>,
) -> impl Responder {let user = UserActiveModel {username: Set(user_data.username.clone()),birthday: Set(user_data.birthday),sex: Set(user_data.sex.clone()),address: Set(user_data.address.clone()),..Default::default()};let result = user.insert(db.get_ref()).await;match result {Ok(user) => HttpResponse::Ok().json(user),Err(_) => HttpResponse::InternalServerError().finish(),}
}
/// 获取指定ID的用户信息
///
/// # 路径参数
///
/// - `id`: 整数,用户ID
///
/// # 响应
///
/// - 成功:返回状态码200和用户JSON对象
/// - 未找到:返回状态码404
/// - 失败:返回状态码500
///
/// # 示例
///
/// ‍‍```
/// GET /users/1
/// ‍‍```
#[utoipa::path(get,path = "/api/users/{id}",responses((status = 200, description = "User found", body = Model),(status = 404, description = "User not found"),(status = 500, description = "Internal server error")),params(("id" = i32, Path, description = "User ID"))
)]
pub async fn get_user(db: web::Data<sea_orm::DatabaseConnection>,id: web::Path<i32>,
) -> impl Responder {let user = user::Entity::find_by_id(*id).one(db.get_ref()).await;println!("{id}");match user {Ok(Some(user)) => HttpResponse::Ok().json(user),Ok(None) => HttpResponse::NotFound().finish(),Err(_) => HttpResponse::InternalServerError().finish(),}
}
/// 更新指定ID的用户信息
///
/// # 路径参数
///
/// - `id`: 整数,用户ID
///
/// # 请求体
///
/// 需要一个JSON对象,包含以下字段(所有字段都是可选的):
/// - `username`: 字符串,新的用户名
/// - `birthday`: ISO 8601格式的日期时间字符串,新的用户生日
/// - `sex`: 字符串,新的用户性别
/// - `address`: 字符串,新的用户地址
///
/// # 响应
///
/// - 成功:返回状态码200和更新后的用户JSON对象
/// - 未找到:返回状态码404
/// - 失败:返回状态码500
///
/// # 示例
///
/// ‍‍```
/// PUT /users/1
/// Content-Type: application/json
///
/// {
///     "username": "johndoe_updated",
///     "address": "456 Elm St, Newtown, USA"
/// }
/// ‍‍```
#[utoipa::path(put,path = "/api/users/{id}",request_body = CreateUser,responses((status = 200, description = "User updated successfully", body = Model),(status = 404, description = "User not found"),(status = 500, description = "Internal server error")),params(("id" = i32, Path, description = "User ID"))
)]
pub async fn update_user(db: web::Data<sea_orm::DatabaseConnection>,id: web::Path<i32>,user_data: web::Json<CreateUser>,
) -> impl Responder {let user = user::Entity::find_by_id(*id).one(db.get_ref()).await;match user {Ok(Some(user)) => {let mut user: UserActiveModel = user.into();user.username = Set(user_data.username.clone());user.birthday = Set(user_data.birthday);user.sex = Set(user_data.sex.clone());user.address = Set(user_data.address.clone());let result = user.update(db.get_ref()).await;match result {Ok(updated_user) => HttpResponse::Ok().json(updated_user),Err(_) => HttpResponse::InternalServerError().finish(),}}Ok(None) => HttpResponse::NotFound().finish(),Err(_) => HttpResponse::InternalServerError().finish(),}
}
/// 删除指定ID的用户
///
/// # 路径参数
///
/// - `id`: 整数,用户ID
///
/// # 响应
///
/// - 成功:返回状态码204(无内容)
/// - 失败:返回状态码500
///
/// # 示例
///
/// ‍‍```
/// DELETE /users/1
/// ‍‍```
#[utoipa::path(delete,path = "/api/users/{id}",responses((status = 204, description = "User deleted successfully"),(status = 500, description = "Internal server error")),params(("id" = i32, Path, description = "User ID"))
)]
pub async fn delete_user(db: web::Data<sea_orm::DatabaseConnection>,id: web::Path<i32>,
) -> impl Responder {let result = user::Entity::delete_by_id(*id).exec(db.get_ref()).await;match result {Ok(_) => HttpResponse::NoContent().finish(),Err(_) => HttpResponse::InternalServerError().finish(),}
}

为了使用Swagger UI查看接口文档,还需要创建src/api_doc.rs文件

rust">#[derive(OpenApi)]
#[openapi(paths(handlers::user::create_user,handlers::user::get_user,handlers::user::update_user,handlers::user::delete_user),components(schemas(Model,CreateUser)),tags((name = "users", description = "User management API"))
)]
pub struct ApiDoc;

在src/main.rs文件定义路由和配置Swagger UI

rust">#[actix_web::main]
async fn main() -> std::io::Result<()> {let db: DatabaseConnection = db::establish_connection().await;let db_data = web::Data::new(db);HttpServer::new(move || {App::new().app_data(db_data.clone()).service(web::scope("/api").service(web::scope("/users").route("", web::post().to(create_user)).route("/{id}", web::get().to(get_user)).route("/{id}", web::put().to(update_user)).route("/{id}", web::delete().to(delete_user)).route("/test", web::get().to(|| async { "Hello, World!" })))).service(SwaggerUi::new("/swagger-ui/{_:.*}").url("/api-docs/openapi.json", ApiDoc::openapi()))}).bind("127.0.0.1:8080")?.run().await
}

到这里,项目完成开发,启动项目

cargo run

查看Swagger UI接口文档

浏览器打开http://localhost:8080/swagger-ui/

在这里插入图片描述

在这里插入图片描述

可以看到我们在Rust代码文件中的注释说明,这对于接口使用人员和代码维护人员都非常友好,当然对于接口的简单测试,在这个页面也是非常方便去进行

查看Rust标准文档

cargo doc --open

在这里插入图片描述

在这里插入图片描述

最后

项目的完整代码可以查看我的仓库​:https://github.com/VinciYan/rusty_crab_api.git

后续,我还会介绍如何使用Rust语言Web开发框架Salvo和SeaORM结合开发WebAPI


http://www.ppmy.cn/news/1526845.html

相关文章

Sybase「退役」在即,某公共卫生机构如何实现 SAP Sybase 到 PostgreSQL 的持续、无缝数据迁移?

使用 TapData&#xff0c;化繁为简&#xff0c;摆脱手动搭建、维护数据管道的诸多烦扰&#xff0c;轻量替代 OGG, Kettle 等同步工具&#xff0c;以及基于 Kafka 的 ETL 解决方案&#xff0c;「CDC 流处理 数据集成」组合拳&#xff0c;加速仓内数据流转&#xff0c;帮助企业…

【计算机网络】IP, 以太网, ARP, DNS

IP, 以太网, ARP, DNS IP协议回顾IP地址报文格式功能介绍地址管理IP地址数量问题初识 NAT 机制通信机制IP数量的解决方案网段划分特殊IP地址 路由选择 以太网协议报文格式源MAC/目的MACMAC地址是什么MAC地址格式MAC的作用 ARPDNS初识DNSDNS主要功能DNS的查询过程 IP协议 回顾I…

c++234继承

#include<iostream> using namespace std;//public 修饰的成员便俩个和方法都能使用 //protected&#xff1a;类的内部 在继承的子类中可使用 class Parents { public:int a;//名字 protected:int b;//密码 private:int c;//情人public:void printT(){cout << &quo…

C语言——数组,指针,指针数组,数组指针

零、存储单元和地址 计算机在保存数据时&#xff0c;把数据放在一个个存储单元中&#xff0c;存储单元可以理解为一个个小房间。 地址就是存储单元&#xff08;小房间&#xff09;的房间号&#xff0c;且这个房间号是唯一的。 详细请学习计算机组成原理3.1 一、变量a int a…

【C++算法】位运算

位运算基础知识 1.基础运算符 << : 左移 >> : 右移 ~ : 取反 & : 按位与&#xff0c;有0就是0 I : 按位或&#xff0c;有1就是1 ^ : 按位异或&#xff0c;&#xff08;1&#xff09;相同为0&#xff0c;相异为1&#xff08;2&#xff09;无进位相加 2.…

【React Native】第三方组件

WebView Picker mode {‘dropdown’} 只在 android 生效 Swiper 搭配 ScrollView 使用 AsyncStorage AsyncStorage.setItem()AsyncStorage.getItem()AsyncStorage.removeItem()AsyncStorage.clear() Geolocation 配置添加获取定位信息的授权许可&#xff0c;在 androi…

双亲委派机制知识点

类加载器 双亲委派模型 为什么采用双亲委派模型 打破双亲委派机制的场景 Tomcat 打破双亲委派机制:目的是可以加载不同版本的jar包 实现类隔离&#xff1a;在Tomcat中&#xff0c;每个Web应用使用独立的类加载器加载类文件&#xff0c;这样做的好处在于&#xff0c;当在同一T…

软件设计师考试笔记

计算机系统知识 计算机硬件基础 1.1 计算机组成原理 • 中央处理器&#xff08;CPU&#xff09;&#xff1a; o CPU是计算机的核心部件&#xff0c;负责执行指令并进行算术与逻辑运算。它由控制单元、运算单元和寄存器组组成。 o 控制单元&#xff08;CU&#xff09;&#xff…