我是一名具有中级C++编程经验的大学生.我想尽快为我的应用程序实现一个简单的基于REST的API.
我查看了卡萨布兰卡和libWebSockets,但在各自网站上发布的示例有点过头了.是否有任何库有更多关于在C++中创建RESTFUL API服务器的面向初学者的教程?
注意:我知道这个问题已在C#中被问过几次,但答案是一年或两年以上,而且大部分都不针对初学者.我希望新帖子能够产生一些新的答案!
Restbed通过ASIO和C++ 11 提供异步客户端/服务器功能.对于那些不喜欢阅读头文件的人,我们会提供很多示例和文档.
#include <memory>
#include <cstdlib>
#include <restbed>
using namespace std;
using namespace restbed;
void post_method_handler( const shared_ptr< Session > session )
{
const auto request = session->get_request( );
int content_length = 0;
request->get_header( "Content-Length", content_length );
session->fetch( content_length, [ ]( const shared_ptr< Session > session, const Bytes & body )
{
fprintf( stdout, "%.*s\n", ( int ) body.size( ), body.data( ) );
session->close( OK, "Hello, World!", { { "Content-Length", "13" } } );
} );
}
int main( const int, const char** )
{
auto resource = make_shared< Resource >( );
resource->set_path( "/resource" );
resource->set_method_handler( "POST", post_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;
}
Run Code Online (Sandbox Code Playgroud)
下一个主要功能将允许依赖注入应用程序层的能力.
auto settings = make_shared< Settings >( );
Service service;
service.add_application_layer( http_10_instance );
service.add_application_layer( http_11_instance );
service.add_application_layer( http2_instance );
service.add_application_layer( spdy_instance );
service.start( settings );
Run Code Online (Sandbox Code Playgroud)
小智 1
嘿,不久前我也是整个 API 游戏的新手。我发现使用 Visual Studio 部署ASP.NET Web API是一个很好的开始方式。VS 提供的模板(我使用的是 2013)使创建自己的控制器变得非常容易。
如果您查找一些有关 HTTP 方法的教程,您就可以真正掌握根据需要塑造控制器的窍门。它们很好地映射到 CRUD 操作,我确信您正在寻求执行这些操作。
您还应该能够找到一个 C++ 库,它允许您调用每个控制器方法并传递/接收序列化的 JSON/XML 对象。希望这有帮助,祝你好运!:)