IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)

RESTful server Address Book Example

Example of how to create a RESTful API server using the https://.

Article lu   fois.

L'auteur

Liens sociaux

Viadeo Twitter Facebook Share on Google+   

RESTful server Address Book Example▲

Image non disponible

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

 
Sélectionnez
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 https://() method is used with the https:// enumeration.

 
Sélectionnez
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 https:// 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:

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

List of Files▲

Files:

List of Files▲

  • addressbookserver/CMakeLists.txt

  • addressbookserver/main.cpp

See Also▲

See also https://

Vous avez aimé ce tutoriel ? Alors partagez-le en cliquant sur les boutons suivants : Viadeo Twitter Facebook Share on Google+   

Ce document est disponible sous la licence https:// telle que publiée par la Free Software Foundation.