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"
 }
相关推荐
智者知已应修善业20 分钟前
【c语言蓝桥杯计算卡片题】2023-2-12
c语言·c++·经验分享·笔记·算法·蓝桥杯
Elias不吃糖2 小时前
NebulaChat项目构建笔记
linux·c++·笔记·多线程
d111111111d2 小时前
STM32外设学习-串口数据包笔记-(程序)
笔记·stm32·单片机·嵌入式硬件·学习
弘毅 失败的 mian3 小时前
编译和链接
c语言·经验分享·笔记·编程入门
aramae4 小时前
MySQL数据库入门指南
android·数据库·经验分享·笔记·mysql
chenzhou__5 小时前
LinuxC语言文件i/o笔记(第十七天)
linux·c语言·笔记·学习
chenzhou__5 小时前
LinuxC语言文件i/o笔记(第十八天)
linux·c语言·笔记·学习
01100001乄夵5 小时前
FPGA模块架构设计完全入门指南
经验分享·笔记·学习方法·fpga入门·fpga学习之路
01100001乄夵5 小时前
FPGA零基础入门:Verilog语法攻略
经验分享·笔记·学习方法·fpga入门·fpga学习之路
受之以蒙5 小时前
Rust ndarray 高性能计算:从元素操作到矩阵运算的优化实践
人工智能·笔记·rust