Skip to content

Instantly share code, notes, and snippets.

@saamerm
Created January 20, 2020 18:36
Show Gist options
  • Save saamerm/c6a7a2277d1f710e93749503f1523dc8 to your computer and use it in GitHub Desktop.
Save saamerm/c6a7a2277d1f710e93749503f1523dc8 to your computer and use it in GitHub Desktop.
Console Application to make a GET String call to a REST API using simple C#!
using System;
using System.Net.Http;
using Newtonsoft.Json;
namespace GetRestAPIJSON
{
class MainClass
{
public static void Main(string[] args)
{
// To use this, you need to add references to "System.Net.Http"
// by right clicking on the References folder-> Add Reference-> System.Net.Http-> OK
var client = new HttpClient();
string json = client.GetStringAsync("https://www.ipinfo.io/json").Result;
Console.WriteLine(json);
// You can end here, or you can parse the data so that you can get individual values from it.
// To use this, you need to add package to "Newtonsoft.JSON"
// by right clicking on the Packages folder-> Manage Nuget Packages-> Newtonsoft.JSON-> OK
var ipinfo = JsonConvert.DeserializeObject<IPInfo>(json);
Console.WriteLine("Your city is " + ipinfo.city);
}
}
// Use http://json2csharp.com/ to get this by pasting in the JSON response from the API
// and just remember to rename "RootObject" to IPInfo
public class IPInfo
{
public string ip { get; set; }
public string city { get; set; }
public string region { get; set; }
public string country { get; set; }
public string loc { get; set; }
public string org { get; set; }
public string postal { get; set; }
public string timezone { get; set; }
public string readme { get; set; }
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment