Inserting Data into Tables from C#

Hi,

I have these two methods, that are made to, with retreived data, push data into a board on monday using C#. When these two methods are called, they are surrounded with a try catch:

private string FormatDataForMonday(List<ResultItem> databaseData)
{
    string mutationTemplate = @"mutation { create_item (board_id: bID, item_name: ""Test"", column_values: {JSON_DATA} ) {id} }";
    string mutationQuery = mutationTemplate.Replace("bID", boardId);

    var formattedData = new
    {
        items = databaseData.Select(dataItem => new
        {
            Site = dataItem.Site,
            EwqPn = dataItem.EwqPn,
        }).ToList()
    };

    // Serializing the entire formattedData, including both Site and EwqPn
    string jsonFormattedData = Newtonsoft.Json.JsonConvert.SerializeObject(formattedData.items);

    mutationQuery = mutationQuery.Replace("{JSON_DATA}", jsonFormattedData);

    return mutationQuery;
}

public async Task<string> QueryMondayApiV2(string query)
{
    byte[] dataBytes = System.Text.Encoding.UTF8.GetBytes(query);

    try
    {
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(MONDAY_API_URL);
        request.ContentType = "application/json";
        request.Method = "POST";
        request.Headers.Add("Authorization", API_KEY);

        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))
        {
            string responseBody = await reader.ReadToEndAsync();

            Console.WriteLine("Request Payload:");
            Console.WriteLine(query);
            Console.WriteLine("Response Body:");
            Console.WriteLine(responseBody);

            return responseBody;
        }
    }
    catch (Exception ex)
    {
        Console.WriteLine($"Error: {ex.ToString()}");
        throw;
    }
}

On the other hand, when I execute it, it catches an error 500. It seems like my JSON is correct, and the error would be triggered by something else. Here is the JSON that is created by FormatDataForMonday(). (The real board_id has been swapped for “boardId”) :

mutation { create_item (board_id: "boardId", item_name: "Test", column_values: [{"Site":"VTI","EwqPn":"1370C-0153A"}] ) {id} }

My board inside monday.com has all the columns that are needed to match what is in the JSON, but I feel like I’m overlooking something. Maybe someone has already ecountered something like this and could help me understand my problem.

Thank you !

Hello there @mfournier and welcome to the community!

I hope you like it here :muscle:

This is the correct syntax for such a mutation:

mutation {
  create_item(
    board_id: 1234567890
    item_name: "Test"
    column_values: "{\"status\":\"Done\",\"text\":\"1370C-0153A\"}"
  ) {
    id
  }
}

Please note that “status” and “text” are the column IDs, and not the column titles.

You can find an example in Postman here.

Hope that helps!

Cheers,
Matias

1 Like

Hi @Matias.Monday

I resolved my problem. Yes it was about the syntax, but it was mostly a problem of strings between C# and GraphQL. Here are my modified methods, that can send values in a board using C# :

private string FormatDataForMonday(List<ResultItem> databaseData)
{
    string mutationQuery = "mutation {create_item(board_id: bID,item_name: \"itemName\",column_values: \"{\\\"txtId1\\\":\\\"txtValue1\\\",\\\"txtId2\\\":\\\"txtValue2\\\"}\") {id}}";
    mutationQuery = mutationQuery.Replace("bID", boardId);
    mutationQuery = mutationQuery.Replace("\"itemName\"", "\"Item API2\"");
    mutationQuery = mutationQuery.Replace("\\\"txtId1\\\"", "\\\"texte\\\"");
    mutationQuery = mutationQuery.Replace("\\\"txtValue1\\\"", "\\\"test texte\\\"");
    mutationQuery = mutationQuery.Replace("\\\"txtId2\\\"", "\\\"texte5\\\"");
    mutationQuery = mutationQuery.Replace("\\\"txtValue2\\\"", "\\\"test texte\\\"");

    return mutationQuery;
}

public async Task<string> QueryMondayApiV2(string query)
{
    try
    {
        using (HttpClient client = new HttpClient())
        {
            client.DefaultRequestHeaders.Add("Authorization", API_KEY);


            var body = new { query = query };
            var response = await client.PostAsJsonAsync(MONDAY_API_URL, body);

            if (response.IsSuccessStatusCode)
            {
                string responseBody = await response.Content.ReadAsStringAsync();
                Console.WriteLine("Response Body:");
                Console.WriteLine(responseBody);

                return responseBody;
            }
            else
            {
                Console.WriteLine($"Error: {response.StatusCode} - {response.ReasonPhrase}");
            }
        }
    }
    catch (Exception ex)
    {
        Console.WriteLine($"Error: {ex.ToString()}");
    }

    return null;
}

Obviously, replacing strings inside of another string isn’t necessary, the text values can be entered directly in the first string.

1 Like

I am glad you found the solution @mfournier !

Thank you for sharing your solution :grin:

2 Likes