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": "[email protected]",
     "first_name": "Jane",
     "last_name": "Doe",
     "avatar": "/img/faces/1-image.jpg"
 }
相关推荐
夏季疯2 分钟前
学习笔记:黑马程序员JavaWeb开发教程(2025.4.7)
java·笔记·学习
麟城Lincoln1 小时前
【Linux笔记】nfs网络文件系统与autofs(nfsdata、autofs、autofs.conf、auto.master)
linux·网络·笔记·nfs·autofs
田梓燊4 小时前
数学复习笔记 12
笔记·线性代数·机器学习
愚润求学4 小时前
【Linux】进程间通信(一):认识管道
linux·运维·服务器·开发语言·c++·笔记
霸王蟹4 小时前
React中useState中更新是同步的还是异步的?
前端·javascript·笔记·学习·react.js·前端框架
霸王蟹4 小时前
React Hooks 必须在组件最顶层调用的原因解析
前端·javascript·笔记·学习·react.js
珊瑚里的鱼4 小时前
【滑动窗口】LeetCode 1658题解 | 将 x 减到 0 的最小操作数
开发语言·c++·笔记·算法·leetcode·stl
请你喝好果汁6416 小时前
Jupyter Notebook 配置学习笔记
笔记·学习·jupyter
Lester_11019 小时前
嵌入式学习笔记 - STM32 ADC 模块工作模式总结
笔记·学习
愚戏师15 小时前
Linux复习笔记(六)shell编程
linux·笔记·shell