How to implement a REST API server with POCO C++ Network Library using JSON?

GutiMac picture GutiMac · Feb 12, 2016 · Viewed 7k times · Source

I have been researching about how to do this and all the examples are with text/html. I have tried implement a server api rest using JSON with POCO C++ network libraries but I am not quite sure if it is the correct way to do this.

void MyHandler::handleRequest(HTTPServerRequest& request,      HTTPServerResponse& response)
{
   response.setStatus(HTTPResponse::HTTP_OK);
   response.setContentType("application/json");

   std::ostream& ostr = response.send();
   string send("true");
   ostr << send;
   response.setContentLength(send.size());
}

Originally it was implemented for hmtl connections as:

void MyHandler::handleRequest(HTTPServerRequest& request,      HTTPServerResponse& response)
{
   response.setStatus(HTTPResponse::HTTP_OK);
   response.setContentType("text/html");

   std::ostream& ostr = response.send();
   ostr << "<html><head><title>HTTPTimeServer powered by POCO C++ Libraries</title>";
   ostr << "<body><p style=\"text-align: center; font-size: 48px;\">";
   ostr << "ConfigHandler";
   ostr << "</p></body></html>";
}

Have I done the change correctly or am I missing something??

If anyone knows of a tutorial about how to build an API REST using JSON with POCO C++ Libraries, it will be very much appreciated.

Thanks in advance.

Answer

edson.a.soares picture edson.a.soares · Jan 5, 2018

Poco C++ Libraries is a great tool for REST APIs building in modern C++, although, regarding the architecture, there are some design decisions to be made.

I made available on GitHub an example of an API project built in C++ using Poco.