How to Write a REST API in C++ in 30 Minutes: A Quick Start

онлайн тренажер по питону

Introduction: Why C++ for REST API?

C++ is traditionally associated with system programming, games, and high-load applications. However, modern C++ (C++17 and C++20 standards) combined with lightweight libraries allows you to create fast and efficient web services. If you need a REST API that processes thousands of requests per second with minimal latency, C++ is an excellent choice.

In this article, we will create a full-fledged REST API in C++ in 30 minutes using the Crow library. This is a mini-framework similar to Python Flask, but written in C++. We will set up routes, learn to parse JSON, and return responses.

Step 1: Environment Setup and Installing Crow

To work, we need a compiler with C++17 support (GCC 7+, Clang 5+, MSVC 2019+) and a dependency manager like vcpkg or Conan. The easiest way is to download Crow as a header-only file.

1.1 Installation via vcpkg (recommended)

If you have vcpkg installed, run the command:

vcpkg install crow

Then, when compiling, specify the path to the libraries:

g++ main.cpp -std=c++17 -I/path/to/vcpkg/installed/x64-linux/include -lpthread -o server

1.2 Manual installation (header-only)

Download the latest version of Crow from GitHub. You only need the file crow_all.h (all-in-one). Place it in your project folder.

Step 2: Creating a Simple Server with Two Endpoints

Let's write a minimal server that listens on port 8080 and responds to GET and POST requests. Create a file main.cpp.

2.1 Basic Server Code

#include "crow_all.h"

int main() {
    crow::SimpleApp app;

    // GET endpoint: root page
    CROW_ROUTE(app, "/")([](){
        return "Hello, REST API on C++!";
    });

    // GET endpoint: /api/status
    CROW_ROUTE(app, "/api/status")([](){
        crow::json::wvalue response;
        response["status"] = "ok";
        response["message"] = "Server is running";
        return response;
    });

    app.port(8080).multithreaded().run();
}

Compile and run:

g++ main.cpp -std=c++17 -lpthread -o api_server
./api_server

Now go to http://localhost:8080/api/status in your browser — you will see a JSON response.

Step 3: Working with JSON and Handling POST Requests

A real REST API involves receiving data from the client. Let's learn to accept JSON in the request body.

3.1 POST Endpoint for Creating a User

#include "crow_all.h"
#include <string>
#include <unordered_map>

int main() {
    crow::SimpleApp app;
    // Simple in-memory storage (for demonstration)
    std::unordered_map<int, std::string> users;
    int next_id = 1;

    // POST /api/users — create a user
    CROW_ROUTE(app, "/api/users").methods("POST"_method)([&](const crow::request& req){
        auto body = crow::json::load(req.body);
        if (!body || !body.has("name")) {
            return crow::response(400, "Missing 'name' field");
        }
        std::string name = body["name"].s();
        int id = next_id++;
        users[id] = name;

        crow::json::wvalue response;
        response["id"] = id;
        response["name"] = name;
        return crow::response(201, response);
    });

    // GET /api/users/{id} — get a user
    CROW_ROUTE(app, "/api/users/<int>")([&](int id){
        auto it = users.find(id);
        if (it == users.end()) {
            return crow::response(404, "User not found");
        }
        crow::json::wvalue response;
        response["id"] = id;
        response["name"] = it->second;
        return crow::response(respon                

Похожие статьи

Книги по Python