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"
 }
相关推荐
程序员夏末5 小时前
【LeetCode | 第七篇】算法笔记
笔记·算法·leetcode
开源盛世!!6 小时前
3.23-3.25笔记
笔记
hanlin037 小时前
刷题笔记:力扣第43、67题(字符串计算)
笔记·算法·leetcode
多看书少吃饭8 小时前
Vue + Java + Python 打造企业级 AI 知识库与任务分发系统(RAG架构全解析)
java·vue.js·笔记
了一梨8 小时前
[T113] 交叉编译 OpenCV 4.5.2 + face 模块
linux·笔记·opencv
困死,根本不会9 小时前
VMware Ubuntu 显示有线连接却无法上网|完整排查与解决笔记
linux·笔记·ubuntu
左左右右左右摇晃9 小时前
数据结构——栈
数据结构·笔记
左左右右左右摇晃10 小时前
数据结构——树
数据结构·笔记
chudonghao11 小时前
[UE学习笔记][基于源码] 理解 Gameplay
c++·笔记·学习·ue5
左左右右左右摇晃12 小时前
数据结构——数组
数据结构·笔记·算法