Giridhar Murali
Giridhar Murali

Reputation: 449

Returning JSON object to HTTP POST REST call from C++

I have a C++ API that is exposed to the web via REST. I have written the applications as FastCGI processes. I am able POST to the apps with data in the body and get back text. But now, instead of text, I want to return data as a JSON object.

I have the output packaged into a JSON file already. I just need to know how to pass this back to the requester.

Edit:

I currently have something like this: http://pastebin.com/vhC30kTJ

In this, I am printing text in the printcontent(string) function. The text I am printing using cout is passed back to the HTTP requester by FastCGI. I want to pass JSON instead, and I have no idea how to do that. I am able to write the data into a JSON file. Do I pass back a JSON file or do I pass back a json style string? I am confused.

Upvotes: 1

Views: 5871

Answers (1)

cdhowie
cdhowie

Reputation: 169318

Ideally, the function forming the JSON should accept a parameter of std::ostream &. Then, if you want to write to a file you pass in an std::ofstream and if you want to write it to standard output (which is what you want to do in this case, so that it gets sent to the browser) you can just pass in std::cout. Make sure you write out the required HTTP headers and the blank line first, or the server/browser will try to interpret the JSON as HTTP headers.

void makejson(ostream & output, string content)
{
    /* output << "{\"some\":\"json\"}" */
}

// Write to file
ofstream file("data.json");
makejson(file, "somedata");
file.close();

// Write to browser
cout << "Content-Type: application/json\r\n\r\n";
makejson(cout, "somedata");

Upvotes: 2

Related Questions