You can create basic RESTful APIs in C++ using various libraries and frameworks that facilitate HTTP communication and JSON processing. Some popular libraries and frameworks for this purpose are:
Here's a step-by-step guide to creating a basic RESTful API using Crow:
First, you need to include Crow in your project. You can do this by cloning the Crow repository and adding it to your project.
git clone <https://github.com/CrowCpp/Crow.git>
Create a new C++ file, for example, main.cpp, and include the Crow header. Define some basic routes for your RESTful API.
#include "crow_all.h"
int main()
{
crow::SimpleApp app;
// Define a simple GET route
CROW_ROUTE(app, "/")([]() {
return "Hello, World!";
});
// Define a route that returns JSON
CROW_ROUTE(app, "/json")
([]() {
crow::json::wvalue x;
x["message"] = "Hello, World!";
return x;
});
// Define a route that accepts a parameter
CROW_ROUTE(app, "/hello/<string>")
([](const std::string& name) {
return "Hello, " + name;
});
// Define a route that accepts POST requests
CROW_ROUTE(app, "/add").methods(crow::HTTPMethod::POST)([](const crow::request& req) {
auto body = crow::json::load(req.body);
if (!body)
return crow::response(400);
int a = body["a"].i();
int b = body["b"].i();
int sum = a + b;
crow::json::wvalue res;
res["sum"] = sum;
return crow::response(res);
});
// Start the server
app.port(18080).multithreaded().run();
}
Compile your project using a C++ compiler. If you're using g++, the command might look something like this:
g++ main.cpp -o my_api -I/path/to/Crow -lpthread
Make sure to replace /path/to/Crow with the actual path to the Crow directory.
Run your application:
./my_api
Your API will now be running on port 18080. You can test the endpoints using a tool like curl or Postman.