Join Troy Miles for an in-depth discussion in this video Converting to JSON data, part of Web Servers and APIs using C++.
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.
- Working with Crow, the C++ micro web framework
- Deploying containers to Heroku
- Building websites and webpages
- Accessing data from a database
- Accessing data via RESTful APIs
- Creating API endpoints
- Running WebSockets on Heroku