Basic C# API v2 Example

Hello fellow humans,

Here’s a basic snippet of C# that let’s you execute queries against the v2 API and return the response as JSON. For some this may be old hat, but it took me a good couple of hours of mucking about - so hopefully it can save someone else that time in the future!

For convenience I’ve created a little helper class to encapsulate the call and return;

using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Threading.Tasks;

namespace Monday.lib
{
	public class MondayHelper
	{
		private const string MondayApiKey = "your-api-key-goes-here";
		private const string MondayApiUrl = "https://api.monday.com/v2/";

		/// <summary>
		/// Get a JSON response from the Monday.com V2 API.
		/// </summary>
		/// <param name="query">GraphQL Query to apply to the Monday.com production instance for Grange.</param>
		/// <returns>JSON response of query results.</returns>
		/// <remarks>
		/// Query must be in JSON,
		///		e.g. = "{\"query\": \"{boards(ids: 1234) {id name}}\"}"
		/// </remarks>
		public async Task<string> QueryMondayApiV2(string query)
		{
			byte[] dataBytes = System.Text.Encoding.UTF8.GetBytes(query);

			HttpWebRequest request = (HttpWebRequest)WebRequest.Create(MondayApiUrl);
			request.ContentType = "application/json";
			request.Method = "POST";
			request.Headers.Add("Authorization", MondayApiKey);

			using (Stream requestBody = request.GetRequestStream())
			{
				await requestBody.WriteAsync(dataBytes, 0, dataBytes.Length);
			}

			using (HttpWebResponse response = (HttpWebResponse)await request.GetResponseAsync())
			using (Stream stream = response.GetResponseStream())
			using (StreamReader reader = new StreamReader(stream))
			{
				return await reader.ReadToEndAsync();
			}
		}
	}

You can then use the helper like so;

var helper = new Monday.lib.MondayHelper();
string json = await helper.QueryMondayApiV2("{\"query\": \"{boards(limit:1){id name}}\"}");

Which will give you the JSON response string to consume as you will.

Note: you don’t need any Nuget Packages or libraries. The only one I’ve used is Newtonsoft’s JSON just so I didn’t have to hand-serialise/deserialise the JSON going in and returning.

1 Like

Amazing @grt-s – thanks so much for sharing!