From the course: Web Servers and APIs using C++

Converting to JSON data - C++ Tutorial

From the course: Web Servers and APIs using C++

Start my 1-month free trial

Converting to JSON data

- [Instructor] JSON is an extremely popular data format. Many web servers, especially those used by JavaScript front-ends like Angular and React, use JSON as their default format. How can we return JSON data from crow? Let's return to Atom. Let's take a look at the contacts handler, and this is contacts plural. It returns a webpage with 10 contacts rendered in an HTML table. We will make a version of it that returns JSON data instead of a webpage. Let's begin by making a copy of the contact's handler. So I'm just going to copy this whole thing, right here. Now I got the whole thing copied. Now remember, there can only be one of every route so instead of calling this one contacts, I'm going to call it api/contacts. I'm gonna go ahead and delete the response object because I'm not gonna need it. And we've got mongo. Skip, skip. Vector. Yeah, that's all fine. And then right here, instead of saying getView, so right now my dto holds my contacts and instead of calling getView on 'em, I'm gonna instead call return crow ::response and these are curly braces, dto. And just for the sake of neatness, I'm gonna move this dto guy down to here. The reason why is just, you should always declare stuff closest as you possibly can to where they're actually used. That is pretty much it. Crow has a constructor for the JSON data. In fact, when it creates a response object from crow::json::wvalue it automatically sets the content type to application JSON, for us. So let's save this. Let's go back to the terminal. Control-C. Let's rebuild and restart the server. Go back to the browser. Now this time I'm gonna call api/contacts and there you go. Here's my data as JSON data. We can validate this in the Restlet Client. So if I come in here and I paste that same route and I say get. Do a send. I get a 200 OK. Right here, it says that it's application/json and here you can see that it is JSON objects. We've got series of key value pairs. That's all there is to creating a JSON endpoint in crow.

Contents