In the first installment in this two-part series on consuming REST services with the Microsoft C++ REST SDK, I explained how to start working with the SDK and the asynchronous features to connect to a REST service and execute a simple HTTP GET request. In this article, I explain how to retrieve and send JSON data, work with asynchronous streams, and the different HTTP methods usually required when interacting with REST services.

Working with JSON

In the previous article, I explained how to execute a simple HTTP GET request. Here, I work with a complex JSON response. I'll use a sample REST service based on the ASP.NET Web API introduced in .NET Framework 4.5 that I explained in Access Data with REST in Windows 8 Apps. This image shows an example of the JSON response produced by an HTTP GET that requests all the groups and their items to the REST service in the popular Fiddler Web debugger.

The following lines show the complete JSON response when you make an HTTP GET request to /api/groups. The response includes six groups. The first group whose Title is Cloud has two items. The other groups don't have items.

The C++ REST SDK uses a single class (web::json::value) to represent JSON values and provides the necessary helpers to assist in serialization. The following code shows an example of a Windows console application that uses the C++ REST SDK to make the HTTP GET call http://localhost:58957/api/groups, and extract the JSON response. Then, the code loops over each JSON element and displays their keys and values by using the helpers provided by the C++ REST SDK.

Before using the code, you need to follow the steps explained in the previous installment for your Visual Studio project and execute the ASP.NET Web API example. In addition, you need to replace http://localhost:58957 with the URI and port on which your REST service is running.

The wmain method in Windows calls the HTTPGetAsync method, which returns a pplx::task<void> instance that represents an asynchronous operation. However, in this case, the HTTPGetAsync method includes many chained asynchronous operations.

Dr. Dobb's encourages readers to engage in spirited, healthy debate, including taking us to task.
However, Dr. Dobb's moderates all comments posted to our site, and reserves the right to modify or remove any content that it determines to be derogatory, offensive, inflammatory, vulgar, irrelevant/off-topic, racist or obvious marketing or spam. Dr. Dobb's further reserves the right to disable the profile of any commenter participating in said activities.

Video

This month's Dr. Dobb's Journal

This month,
Dr. Dobb's Journal is devoted to mobile programming. We introduce you to Apple's new Swift programming language, discuss the perils of being the third-most-popular mobile platform, revisit SQLite on Android
, and much more!