使用 Rust 构建 GraphQL API:面向初学者的分步教程

面向初学者的在线Python训练器

轻松学习Python,无需理论负担。在浏览器中直接解决带自动检查的实践任务,无需安装任何东西。

开始课程

GraphQL API 在 Rust 中的介绍

现代 Web 开发需要灵活且高性能的 API。GraphQL 是一种查询语言,允许客户端精确获取所需数据,避免冗余。而 Rust 则提供了高性能和内存安全性。在本教程中,我们将使用 async-graphql 库在 Rust 中创建一个简单但功能完整的 GraphQL 服务器。您将学习如何配置项目、定义数据类型、编写解析器以及启动服务器。本文面向熟悉 Rust 基础的初级开发者。



项目配置与依赖安装

首先,使用 Cargo 创建一个新的 Rust 项目:

cargo new graphql-rust-tutorialcd graphql-rust-tutorial

打开 Cargo.toml 文件并添加以下依赖:

[dependencies]async-graphql = "7.0"async-graphql-actix-web = "7.0"actix-web = "4"serde = { version = "1.0", features = ["derive"] }tokio = { version = "1", features = ["full"] }

解释一下库的选择:

  • async-graphql — 在 Rust 中处理 GraphQL 的核心库。
  • async-graphql-actix-web — 与 Web 框架 Actix-web 的集成。
  • actix-web — 流行的异步 HTTP 服务器。
  • serde — 用于数据的序列化/反序列化。
  • tokio — 异步运行时。

运行 cargo build 以确保所有依赖正确安装。



定义 GraphQL 模式与解析器

让我们创建一个简单的数据模型——书籍。定义结构体以及用于查询和变更的解析器。

创建数据模型

创建文件 src/models.rs 并添加以下代码:

use async_graphql::*;

#[derive(SimpleObject)]pub struct Book { pub id: ID, pub title: String, pub author: String,}

#[derive(InputObject)]pub struct NewBook { pub title: String, pub author: String,}

这里,SimpleObject 自动为 Book 结构体生成 GraphQL 类型,而 InputObject 则为变更的输入数据生成类型。



创建存储与解析器

创建文件 src/resolvers.rs,其中包含查询和变更的逻辑:

use std::sync::Mutex;use async_graphql::*;use crate::models::{Book, NewBook};

pub struct QueryRoot;

#[Object]impl QueryRoot { async fn books(&self) -> Vec<Book> { let storage = STORAGE.lock().unwrap(); storage.clone() }

async fn book(&self, id: ID) -> Option<Book> { let storage = STORAGE.lock().unwrap(); storage.iter().find(|b| b.id == id).cloned() }}

pub struct MutationRoot;

#[Object]impl MutationRoot { async fn add_book(&self, input: NewBook) -> Book { let mut storage = STORAGE.lock().unwrap(); let new_book = Book { id: ID::from(format!("book_{}", storage.len() + 1)), title: input.title, author: input.author, }; storage.push(new_book.clone()); new_book }}

lazy_static::lazy_static! { static ref STORAGE: Mutex<Vec<Book>> = Mutex::new(vec![]);}

请注意:我们使用 Mutex 来实现对存储的线程安全访问。在实际项目中,最好使用数据库。



组装模式

现在,将所有内容整合到 src/main.rs 文件中:

use actix_web::{web, App, HttpServer, HttpResponse, middleware};use async_graphql::{http::GraphiQLSource, EmptySubscription, Schema};use async_graphql_actix_web::{GraphQLRequest, GraphQLResponse};use std::sync::Arc;

mod models;mod resol

博客

书籍推荐