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"
 }
相关推荐
_落纸1 天前
三大基础无源电子元件——电阻(R)、电感(L)、电容(C)
笔记
Alice-YUE1 天前
【CSS学习笔记3】css特性
前端·css·笔记·html
2303_Alpha1 天前
SpringBoot
笔记·学习
Hello_Embed1 天前
STM32HAL 快速入门(二十):UART 中断改进 —— 环形缓冲区解决数据丢失
笔记·stm32·单片机·学习·嵌入式软件
咸甜适中1 天前
rust语言 (1.88) 学习笔记:客户端和服务器端同在一个项目中
笔记·学习·rust
Grassto1 天前
RAG 从入门到放弃?丐版 demo 实战笔记(go+python)
笔记
Magnetic_h1 天前
【iOS】设计模式复习
笔记·学习·ios·设计模式·objective-c·cocoa
周周记笔记1 天前
学习笔记:第一个Python程序
笔记·学习
丑小鸭是白天鹅1 天前
Kotlin协程详细笔记之切线程和挂起函数
开发语言·笔记·kotlin
潘达斯奈基~1 天前
《大数据之路1》笔记2:数据模型
大数据·笔记