UK National Holidays API

 

The UK Government have a useful web page for all of the UK’s National Holidays, such as Easter and Christmas. This can be found with the link here https://www.gov.uk/bank-holidays. In addition to this, there is also a really handy public API, which is the JSON representation of the web page (Just add .json to the end of the URL).

I was recently writing an application where I needed to populate and store bank holidays in the system, so I wrote a simple helper to read the data from the API and populate the necessary tables. It is simple, but it is effective.

To generate the C# objects, I used Visual Studio’s really useful in-built conversion tool. This allows you to copy and paste the JSON straight from the source straight into the IDE. Visual Studio then auto-magically converts it to all the necessary C# objects and their dependencies. It’s by no means perfect in that you will need to do a bit of tidying up here and there, but it takes care of most of the effort involved.

 

Pasting JSON into Visual Studio

 

In my example below, it uses Newtonsoft JSON.NET, which is a NUGET package. In order to use this you would need to right-mouse click on your project in Visual Studio and click ‘Manage Nuget packages’. From here, you should be able to search and add JSON.NET as a dependency. Once added, any reference errors can be rectified easily by using the shortcut key [ctrl] + [fullstop] over the offending line(s) of code.


// Using System.Net
// NewtonSoft JSON.NET
private static BankHolidays GetUkGovBankHolidays()
{
	string apiEndPoint = "https://www.gov.uk/bank-holidays.json";
	BankHolidays apiHolidays = null;

	using (var wb = new WebClient())
	{
		wb.Encoding = Encoding.UTF8;
		string response = wb.DownloadString(apiEndPoint);
		apiHolidays = JsonConvert.DeserializeObject(response);
	}

	
	return apiHolidays;
}

#region "Government UK Bank Holiday API Classes"
protected class BankHolidays
{
	[JsonProperty("england-and-wales")]
	public BankHolidayDivision EnglandAndWales { get; set; }

	[JsonProperty("scotland")]
	public BankHolidayDivision Scotland { get; set; }

	[JsonProperty("northern-ireland")]
	public BankHolidayDivision NorthernIreland { get; set; }
}

protected class BankHolidayDivision
{
	[JsonProperty("division")]
	public string Division { get; set; }

	[JsonProperty("events")]
	public List Events { get; set; }
}

protected class Event
{
	[JsonProperty("title")]
	public string Title { get; set; }

	[JsonProperty("date")]
	public DateTime Date { get; set; }

	[JsonProperty("notes")]
	public string Notes { get; set; }

	[JsonProperty("bunting")]
	public bool Bunting { get; set; }
}
#endregion

With the example provided it will produce a list of holidays for England/Wales, Scotland and Northern Ireland. It will also include historic as well as future holidays. During my testing, it provided a range of 6 years behind and 1 year ahead.

 

Post Categories