
C语言快速上手RESTful API开发指南|Ulfius + Jansson实战教程
由于 Rust 具备高性能、安全性和强大的并发能力,使用 Rust 构建 REST API 已成为开发者的热门选择。本指南将详细介绍如何使用 Rust 创建 RESTful API,从环境设置到最终部署的完整流程。通过本文,您将学会构建高效、可靠的 REST API,能够处理高并发流量并为用户提供稳定服务。
在开始之前,需要在系统上安装 Rust。推荐使用 rustup
工具链安装程序完成安装。打开终端并运行以下命令:
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
按照屏幕提示完成安装后,运行以下命令验证安装是否成功:
rustc --version
Rust 自带的包管理器和构建系统 Cargo
将帮助我们创建项目。在终端中运行以下命令创建一个新的 Rust 项目:
cargo new rest_api --bin
cd rest_api
上述命令会生成一个名为 rest_api
的目录,其中包含基本的 Rust 项目结构。
Rust 提供多种 Web 框架用于构建 REST API,包括 Rocket、Actix Web 和 Warp。本指南选择性能和灵活性兼备的 Actix Web。
在项目目录中的 Cargo.toml
文件添加依赖:
[dependencies]
actix-web = "4.0"
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"
uuid = "1.0"
dotenv = "0.15"
在 src/main.rs
中创建一个基本服务器以验证环境:
use actix_web::{web, App, HttpServer, Responder};
async fn hello() -> impl Responder {
"Hello, world!"
}
#[actix_web::main]
async fn main() -> std::io::Result<()> {
HttpServer::new(|| {
App::new().route("/", web::get().to(hello))
})
.bind("127.0.0.1:8080")?
.run()
.await
}
运行以下命令启动服务器:
cargo run
访问 http://127.0.0.1:8080
,浏览器应显示 Hello, world!。
创建 src/models.rs
文件,定义 API 数据结构:
use serde::{Serialize, Deserialize};
use uuid::Uuid;
#[derive(Serialize, Deserialize)]
pub struct Item {
pub id: Uuid,
pub name: String,
pub description: String,
}
创建 src/handlers.rs
文件,处理 API 请求:
use actix_web::{web, HttpResponse};
use uuid::Uuid;
use serde_json::json;
use crate::models::Item;
pub async fn create_item(item: web::Json<Item>) -> HttpResponse {
HttpResponse::Ok().json(item.into_inner())
}
pub async fn get_items() -> HttpResponse {
let items = vec![
Item {
id: Uuid::new_v4(),
name: String::from("Item 1"),
description: String::from("Description 1"),
},
Item {
id: Uuid::new_v4(),
name: String::from("Item 2"),
description: String::from("Description 2"),
},
];
HttpResponse::Ok().json(items)
}
pub async fn get_item(item_id: web::Path<Uuid>) -> HttpResponse {
let item = Item {
id: *item_id,
name: String::from("Item 1"),
description: String::from("Description 1"),
};
HttpResponse::Ok().json(item)
}
pub async fn update_item(item_id: web::Path<Uuid>, item: web::Json<Item>) -> HttpResponse {
let mut updated_item = item.into_inner();
updated_item.id = *item_id;
HttpResponse::Ok().json(updated_item)
}
pub async fn delete_item(item_id: web::Path<Uuid>) -> HttpResponse {
HttpResponse::Ok().json(json!({ "deleted": item_id.to_string() }))
}
更新 src/main.rs
:
mod handlers;
mod models;
use actix_web::{web, App, HttpServer};
use dotenv::dotenv;
use std::env;
#[actix_web::main]
async fn main() -> std::io::Result<()> {
dotenv().ok();
let database_url = env::var("DATABASE_URL").expect("DATABASE_URL must be set");
HttpServer::new(|| {
App::new()
.service(
web::scope("/api")
.route("/items", web::post().to(handlers::create_item))
.route("/items", web::get().to(handlers::get_items))
.route("/items/{id}", web::get().to(handlers::get_item))
.route("/items/{id}", web::put().to(handlers::update_item))
.route("/items/{id}", web::delete().to(handlers::delete_item))
)
})
.bind("127.0.0.1:8080")?
.run()
.await
}
使用 curl
或 Postman
测试 API。
创建新项目:
curl -X POST http://127.0.0.1:8080/api/items \
-H "Content-Type: application/json" \
-d '{"id": "550e8400-e29b-41d4-a716-446655440000", "name": "Item 1", "description": "Description 1"}'
获取所有项目:
curl http://127.0.0.1:8080/api/items
获取单个项目:
curl http://127.0.0.1:8080/api/items/550e8400-e29b-41d4-a716-446655440000
更新项目:
curl -X PUT http://127.0.0.1:8080/api/items/550e8400-e29b-41d4-a716-446655440000 \
-H "Content-Type: application/json" \
-d '{"name": "Updated Item 1", "description": "Updated Description 1"}'
删除项目:
curl -X DELETE http://127.0.0.1:8080/api/items/550e8400-e29b-41d4-a716-446655440000
构建优化版本:
cargo build --release
Rust API 可部署至 Heroku、AWS、DigitalOcean 或 Google 云平台。建议使用 .env
文件管理环境变量:
DATABASE_URL=postgres://user:password@localhost/dbname
加载环境变量:
use dotenv::dotenv;
use std::env;
dotenv().ok();
let database_url = env::var("DATABASE_URL").expect("DATABASE_URL must be set");
通过本指南,您已掌握使用 Rust 构建高性能 REST API 的完整流程。Rust 的安全性、并发能力和性能优势使其成为现代 Web 服务开发的理想选择。
原文链接: https://medium.com/@rs4528090/how-to-build-a-rest-api-with-rust-65dfb19d1edd