Qt6文档阅读笔记-RESTful API Server解析

本例使用QHttpServer创建RESTful API服务端。

此例接收REST风格的请求,与此例与之对应的客户端是RESTful Color Palette API client。

满足REST限制的API被称为RESTful风格的API。

RESTful API服务端一般包括:create、read、update、delete操作。

其中部分操作需要RESTful服务端提供login/logout功能。

执行服务端的二进制程序的命令:

bash 复制代码
./colorpaletteserver

bash 复制代码
./colorpaletteserver --port 1234

上面命令中port参数提供了指定服务端开放的tcp端口的功能。

cpp 复制代码
 httpServer.route(
         QString("%1").arg(apiPath), QHttpServerRequest::Method::Get,
         [&api](const QHttpServerRequest &request) { return api.getPaginatedList(request); });

上例中,route指定GET方法,以JSON数组的形式返回当前提供的页码的数据。其中QHttpServer::route()中使用QHttpServerRequest::Method::Get枚举类型,指明这个route为GET方法。

cpp 复制代码
 httpServer.route(QString("%1/<arg>").arg(apiPath), QHttpServerRequest::Method::Get,
                  [&api](qint64 itemId) { return api.getItem(itemId); });

上面的代码通过请求中的ID参数,获取list实例中单独的那条。

cpp 复制代码
httpServer.route(QString("%1/<arg>").arg(apiPath), QHttpServerRequest::Method::Get,
                  [&api](qint64 itemId) { return api.getItem(itemId); });

上例中,route接收POST方法,新增一个实例,并且返回新增的实例。此请求必须被认证,认证的token需要放到请求的head中,其中token为调用服务端api/login和api/register返回的数据。

cpp 复制代码
 QHttpServerResponse postItem(const QHttpServerRequest &request)
 {
     const std::optional<QJsonObject> json = byteArrayToJsonObject(request.body());
     if (!json)
         return QHttpServerResponse(QHttpServerResponder::StatusCode::BadRequest);

     const std::optional<T> item = factory->fromJson(*json);
     if (!item)
         return QHttpServerResponse(QHttpServerResponder::StatusCode::BadRequest);
     if (data.contains(item->id))
         return QHttpServerResponse(QHttpServerResponder::StatusCode::AlreadyReported);

     const auto entry = data.insert(item->id, *item);
     return QHttpServerResponse(entry->toJson(), QHttpServerResponder::StatusCode::Created);
 }

上面的postItem函数中返回了不同HTTP状态。上例中利用QHttpServerResponse::QHttpServerResponse方法传输过来的json对应,与HTTP状态相关做对应。

创建一个实例,请求题需要包含email、first_name、last_name、avatar这类json对象。

javascript 复制代码
 {
     "email": "jane.doe@qt.io",
     "first_name": "Jane",
     "last_name": "Doe",
     "avatar": "/img/faces/1-image.jpg"
 }
相关推荐
不会代码的小猴6 小时前
C++的第九天笔记
开发语言·c++·笔记
我命由我123457 小时前
开发中的英语积累 P19:Inspect、Hint、Feedback、Direction、Compact、Vulnerability
经验分享·笔记·学习·职场和发展·求职招聘·职场发展·学习方法
老王熬夜敲代码8 小时前
C++中的thread
c++·笔记·面试
崇山峻岭之间9 小时前
C++ Prime Plus 学习笔记033
c++·笔记·学习
暗然而日章9 小时前
C++基础:Stanford CS106L学习笔记 7 类
c++·笔记·学习
思成不止于此9 小时前
【MySQL 零基础入门】DDL 核心语法全解析:数据库与表结构操作篇
数据库·笔记·学习·mysql
lkbhua莱克瓦249 小时前
Java进阶——IO流
java·开发语言·笔记·学习方法·io流
浦东新村轱天乐9 小时前
2025.12.01-2025.12.07:休假回来,开始迭代vlm
笔记
im_AMBER9 小时前
Leetcode 72 数组列表中的最大距离
c++·笔记·学习·算法·leetcode
FFF团团员9099 小时前
树莓派学习笔记7:局域网的建立和程序自启动
笔记·学习