How to Write a REST API in C++ in 30 Minutes: A Practical Guide

Online Python Trainer for Beginners

Learn Python easily without overwhelming theory. Solve practical tasks with automatic checking, get hints in Russian, and write code directly in your browser — no installation required.

Start Course

Introduction: Why C++ for REST API is No Joke

\n

C++ is traditionally associated with system programming, games, and high-performance computing. However, in recent years, this language is increasingly used for creating web services and REST APIs. Why? Because C++ provides incredible performance and memory control, which is critical for high-load backend solutions.

\n

In this guide, we will create a full-fledged REST API in C++ in 30 minutes using the cpp-httplib library (a single header library, no installation required). You will learn:

\n
    \n
  • How to set up an HTTP server in C++
  • \n
  • How to handle GET, POST, PUT, and DELETE requests
  • \n
  • How to work with JSON via nlohmann/json
  • \n
  • How to build and run the project
  • \n
\n

This material is suitable for both beginners and experienced developers who want to try C++ in web development.

\n\n

Step 1: Environment Setup and Dependency Installation

\n

For this, we will need:

\n
    \n
  • A C++ compiler (g++ or clang) with C++17 support
  • \n
  • The cpp-httplib library (a single h-file)
  • \n
  • The nlohmann/json library (a single hpp-file)
  • \n
\n

Download both libraries:

\n
# Install cpp-httplib\nwget https://raw.githubusercontent.com/yhirose/cpp-httplib/master/httplib.h\n\n# Install nlohmann/json\nwget https://raw.githubusercontent.com/nlohmann/json/develop/single_include/nlohmann/json.hpp
\n

The project structure will be simple:

\n
my_rest_api/\n├── main.cpp\n├── httplib.h\n└── json.hpp
\n\n

Step 2: Creating a Basic HTTP Server

\n

Let's start with a minimal server that listens on port 8080 and responds to GET requests.

\n

Create the file main.cpp:

\n
#include "httplib.h"\n#include "json.hpp"\n#include <iostream>\n\nusing namespace httplib;\nusing json = nlohmann::json;\n\nint main() {\n    Server svr;\n\n    // GET request to the root\n    svr.Get("/", [](const Request& req, Response& res) {\n        res.set_content("Hello, REST API on C++!", "text/plain");\n    });\n\n    std::cout << "Server started on http://localhost:8080" << std::endl;\n    svr.listen("0.0.0.0", 8080);\n\n    return 0;\n}
\n

Compile and run:

\n
g++ -std=c++17 -pthread -o server main.cpp\n./server
\n

Open a browser or use curl http://localhost:8080 — you will see a welcome message. The server is working!

\n\n

Step 3: Implementing CRUD Operations with JSON

\n

Now let's add in-memory data storage (a simple vector) and implement a full REST API for working with users.

\n

Updated main.cpp:

\n
#include "httplib.h"\n#include "json.hpp"\n#include <iostream>\n#include <vector>\n#include <string>\n#include <sstream>\n\nusing namespace httplib;\nusing json = nlohmann::json;\n\n// User model\nstruct User {\n    int id;\n    std::string name;\n    std::string email;\n};\n\n// In-memory database\nstd::vector<User> users;\nint next_id = 1;\n\nint main() {\n    Server svr;\n\n    // POST /users - create a user\n    svr.Post("/users", [](const Request& req, Response& res) {\n        try {\n            auto data = json::parse(req.body);\n            User u;\n            u.id = next_id++;\n            u.name = data["name"];\n            u.email = data["email"];\n            users.push_back(u);\n\n            json response = {{"id", u.id}, {"name", u.name}, {"email", u.email}};\n            res.set_content(response.dump(), "application/json");\n        } catch (...) {\n            res.status = 400;\n            res.set_content("{\\"error\\":\\"Invalid JSON\\"}", "application/json");\n        }\n    });\n\n    // GET /users - list all users\n    svr.Get("/users", [](const Request& req, Response& res) {\n                

Blogs

Book Recommendations