How to Create Restful Web Services using c++ language and JSON Parser How to Create Restful Web Services using c++ language and JSON Parser linux linux

How to Create Restful Web Services using c++ language and JSON Parser


Restbed can address your requirements with the exception of a JSON parser. However, combining a solution with one of the many C++ JSON implementations already available requires very little work.

#include <memory>#include <string>#include <cstdlib>#include <sstream>#include <jsonbox.h>#include <restbed>using namespace std;using namespace restbed;void get_method_handler( const shared_ptr< Session > session ){    const auto request = session->get_request( );    size_t content_length = request->get_header( "Content-Length", 0 );    session->fetch( content_length, [ ]( const shared_ptr< Session >& session, const Bytes& body )    {        JsonBox::Value json;        json.loadFromString( string( body.begin( ), body.end( ) ) );        //perform awesome solutions logic...        stringstream stream;        json.writeToStream( stream );        string response_body = stream.str( );        session->close( OK, response_body, { { "Content-Length", ::to_string( response_body.length( ) }, { "Content-Type": "application/json" } } );    } );}int main( const int, const char** ){    auto resource = make_shared< Resource >( );    resource->set_path( "/resource" );    resource->set_method_handler( "GET", get_method_handler );    auto settings = make_shared< Settings >( );    settings->set_port( 1984 );    settings->set_default_header( "Connection", "close" );    Service service;    service.publish( resource );    service.start( settings );    return EXIT_SUCCESS;}

Alternative RESTful frameworks

Alternative JSON frameworks


I know this is late, but something new has come up a year or two ago.

If you're into hardcore asynchronous programming for high-performance, you can consider boost::beast. It's a layer above boost::asio (the generic tcp/udp and i/o library) that has both http(s) and websocket servers/clients.

Keep in mind that these are ideal for performance and full freedom in multithreading (you can literally run your server on thousands of threads with almost perfect caching if you have a server that can take it), but they have a steep learning-curve. Do this only if you need to have absolute control over everything!


I'm using oatpp in combination with nlohmann JSON. Though you may get away with purely oatpp as it has built-in JSON handling features. Please, see a step by step guide.