RESTful server Address Book Example

Example of how to create a RESTful API server using the QHttpServer.

This example shows how to set up a RESTful API server using the QHttpServer class. The Address Book API allows create, read, update and delete operations of name and address entries.

httpServer.route("/v2/contact", QHttpServerRequest::Method::Get,
                 [&contacts](const QHttpServerRequest &) {
                     QJsonArray array;
                     std::transform(contacts.cbegin(), contacts.cend(),
                                    std::inserter(array, array.begin()),
                                    [](const auto &it) { return it.toJson(); });

                     return QHttpServerResponse(array);
                 });

In the example above, the route is specified for the GET method, which returns the JSON array with all address entries stored. To achieve that, the QHttpServer::route() method is used with the QHttpServerRequest::Method::Get enumeration.

httpServer.route(
        "/v2/contact", QHttpServerRequest::Method::Post,
        [&contacts](const QHttpServerRequest &request) {
            if (!checkApiKeyHeader(request.headers())) {
                return QHttpServerResponse(QHttpServerResponder::StatusCode::Unauthorized);
            }
            const auto json = byteArrayToJsonObject(request.body());
            if (!json || !json->contains("address") || !json->contains("name"))
                return QHttpServerResponse(QHttpServerResponder::StatusCode::BadRequest);
            const auto entry = insertAddress(contacts, json->value("name").toString(),
                                             json->value("address").toString());
            return QHttpServerResponse(entry, QHttpServerResponder::StatusCode::Created);
        });

In this example, the route is specified for the POST method, which adds a new entry to the address book and returns a JSON object that represents the added entry. This JSON object also contains an HTTP status code: Created for new entries, or AlreadyReported for pre-existing entries. This example makes use of an overload of QHttpServerResponse::QHttpServerResponse to send a JSON object and corresponding HTTP status code.

To create an entry the request body must be a JSON object with address and name fields. For example:

{
    "address": "Example Street 1, Big City"
    "name": "John Smith"
}

Files:

See also Qt Quick Demo - RESTful API client Address Book.

© 2022 The Qt Company Ltd. Documentation contributions included herein are the copyrights of their respective owners. The documentation provided herein is licensed under the terms of the GNU Free Documentation License version 1.3 as published by the Free Software Foundation. Qt and respective logos are trademarks of The Qt Company Ltd. in Finland and/or other countries worldwide. All other trademarks are property of their respective owners.