How to Create Restful Web Services using c++ langu

2019-03-08 02:19发布

问题:

I am working on Embedded Linux and I want Restful web services to run on my Linux Custom Board.

My objective is to send/receive data (in JSON format) to/from web server (httpd server).

Also, I want to create that Restful Web services using C++ language.

Please see below idea about need of Restful Web Services for my Linux Custom Board.

  1. First, I will send HTTP request with JSON format data through httpd server which is running on my linux board.

  2. Then, I want to create one binary or server which implements this Restful Web Services in c++ language which is used to handle HTTP request.

  3. Then, This C++ binary will send response back to httpd server for display purpose over web browser.

Does anyone have idea or example about how to create Restful Web Services using C++ language?

Any help on Restful is welcome.

Does any one has idea about ffead and its functionalities which fulfills my Restful Web Services or not?

回答1:

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

  • Casablanca
  • CPP-Netlib
  • RESTful Mapper
  • Simple REST
  • Google is your friend.

Alternative JSON frameworks

  • LibJSON
  • RapidJSON
  • JSONMe
  • JSON++
  • JSON-CPP
  • Google is your friend.


回答2:

If you are using Apache2 or Nginx as Web server and want to deploy RESTful JSON Web services on it, try ngrest. It's easy in use and fast.

To represent JSON in C++ ngrest uses standard C++ types (generic types, C++ structs, typedefs, STL containers, etc.). Access to raw JSON is possible too. Optionally you can access DBMS using ngrest-db extension.

An example of typical workflow of creating the C++ service:

1) create a service (it may be implemented as h/cpp or single hpp file):

ngrest create -d hpp Users

2) implement data structures and operations (resources). Edit users/users/src/Users.hpp like that:

// a structure to represent data in JSON
struct User {
    int id;
    std::string name;
    std::string email;
};

// *location: /users
class Users: public ngrest::Service
{
public:
    // *method: POST
    int add(const User& user) {
        return Db::inst().users().insert(user).lastInsertId();
    }

    // *location: /{id}
    User get(int id) {
        return Db::inst().users().selectOne("id = ?", id);
    }

    // *method: DELETE
    void remove(int id) {
        Db::inst().users().deleteWhere("id = ?", id);
    }
};

3) run your service for the test:

cd users
ngrest

4) test your RESTful Web service using service tester: http://localhost:9098/ngrest/service/users

5) deploy your Web Service library to the Web Server running ngrest.



回答3:

If you are building a RESTful service client, you should consider a library such as Casablanca (which is maintained by Microsoft and is a cross-platform solution for accessing RESTful APIs) https://github.com/Microsoft/cpprestsdk.

Otherwise you could also use libcurl https://curl.haxx.se/libcurl

There are C++ bindings for curl. Depending on your board, libcurl might already be installed. All you have to do would be to use the C++ bindings.

Both libraries handle http/https. libcurl does not provide a json parser but you could easily combine it with any C++ json parser available. Casablanca is complete and built on an asynchronous model. It relies however on the Boost libraries. Nevertheless I have used on an Intel Edison board with success.



回答4:

For send/receive data in JSON format, try jsoncpp



回答5:

Use an embedded web server, such as Mongoose, CivetWeb or NXWeb. (see this post for more details)

Generally these are trivial to embed in your application, then you only need a JSON library to parse/create JSON data in the web server route handlers. REST is, after all, only HTTP requests so this is easy to implement using one of the above.



回答6:

There are some frameworks like CppCMS that embed their own HTTP server, so you might not need something as heavy as Apache httpd.

I'm assuming your REST service will not be under heavy load.

Also, CppCMS supports JSON out of the box, see http://cppcms.com/wikipp/en/page/cppcms_1x_json.



回答7:

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!



回答8:

Probably your best bet is to use FastCGI to create a module to interface with your web server. This should prevent you from having to implement your own HTTP server.