Skip to content

Simple JSON API Calls In C# In 10 Minutes

github source for this project

Note: This starts from scratch and integrates with the Sunlight Foundation Congress API in a few short minutes. It is not designed to model good architecture or best practices.

So you’ve got an API that delivers a JSON object or array & you want to access this in C# and you want to get this done really fast. This post is valid for UWP / Windows 8.1 / Xamarin apps. In this example, I’m going to use the Sunlight Foundation Congress API.

Step 1: Create a C# object (model) based on the JSON result

If possible, find a JSON sample of the result you’re looking for. I went to the Sunlight Congress API and searched for every legislator named “Robert”.

APIPost1 APIPost2

Now select the result, copy it and paste it into Json2CSharp and it will convert it into a C# class.

Create a new model in your app & create a new class. Copy and paste the C# class into your class. We’re going to rename the “Result” class to be “Legislator” and the “Page” class to “ApiPage” for the sake of clarity. You’ll have to change “Result” to “Legislator” in the RootObject class at the bottom as well.

API Call 3

Step 2: Create a Static Service Call

Create a new class for making the API call. I called mine “LegislatorSearch.cs”.

Add a static async method, a string for the url of your API call and a string for your API key.

GEtLegislator

Now add an HttpClient object. It won’t resolve, so place your cursor in the HttpClient text and press Alt-Shift-F10 to add a reference to “System.Net.Http” to your class.

APICall HTTP Client

Now we need to add JSON.Net to make this really, really easy. Open your “Package Manager Console” (type “Package Manager” into the Quick Launch box at the top left of Visual Studio.

Type “Install-Package Newtonsoft.Json”

Install Newtonsoft

Now go back to your LegislatorSearch class and add the following code.

LegislatorGet

There! This is working. You can call the following method to get a list of legislators with a first name search term.

GEtLegislatorCall