Write your own REST Web Server using C++ using CPP REST SDK (casablanca)

To start, you have to download the C++ REST SDK from Github. It enables to build the library. Just open the sln file in the root folder, restore nuget packages and  and that's all. Build.

The compilation results in a 4,9 MB file. Now you can build your own web server. You just have to include some headers.

  • #include "cpprest/json.h"
  • #include "cpprest/http_listener.h"
  • #include "cpprest/uri.h"
  • #include "cpprest/asyncrt_utils.h"

The namespaces to use are:

  • using namespace web;
  • using namespace http;
  • using namespace utility;
  • using namespace http::experimental::listener;

The first thing is to declare is a uri_builder object. In my case, this is "https://localhost:34568/MyServer/Action/".  Now we can create a MyServer class that exposes end points.

The class contains an http_listener element.

Here the implementation of the server. First, in the constructor, we expose all the end-points. In this implementation, the end-points return OK. But you can return JSON data, it is supported by the C++ REST SDK. The missing part is the wmain who instanciate the MyServer class...

As you can see, it is very simple. One handler for each verb and you are are on line.

The source code is available here.