How to make a POST request to OpsGenie? How to make a POST request to OpsGenie? curl curl

How to make a POST request to OpsGenie?


It might be easier to use WebClient for a task like this. It has a number of helper methods that make downloading and uploading content like strings really easy.

Also, instead of trying to build the JSON payload by concatenating strings, just use Newtonsoft.Json.

I refactored your method to use WebClient and JsonConvert. It's a lot simpler now! I left the debugging in place, but you can remove the console logging lines after you've tested it:

public static void CreateAlert(string api, string message, string description, string entity, string[] teams,    string user, string[] tags){    // Serialize the data to JSON    var postData = new    {        apiKey = api,        message,        teams    };    var json = JsonConvert.SerializeObject(postData);    // Set up a client    var client = new WebClient();    client.Headers.Add("Content-Type", "application/json");    try    {        var response = client.UploadString("https://api.opsgenie.com/v1/json/alert", json);        Console.WriteLine("Success!");        Console.WriteLine(response);    }    catch (WebException wex)    {        using (var stream = wex.Response.GetResponseStream())        using (var reader = new StreamReader(stream))        {            // OpsGenie returns JSON responses for errors            var deserializedResponse = JsonConvert.DeserializeObject<IDictionary<string, object>>(reader.ReadToEnd());            Console.WriteLine(deserializedResponse["error"]);        }    }}


Since API v1 is now deprecated, the above solution should look like:

public static void CreateAlert(string api, string message,string description, string entity, string[] teams,string user, string[] tags){ // Serialize the data to JSON    var postData = new    {        apiKey = api,        message,        teams    };    var json = JsonConvert.SerializeObject(postData);    // Set up a client    var client = new WebClient();    client.Headers.Add("Content-Type", "application/json");    client.Headers.Add("Authorization", $"GenieKey {api}");    try    {        var response = client.UploadString("https://api.opsgenie.com/v2/alerts", json);        Console.WriteLine("Success!");        Console.WriteLine(response);    }    catch (WebException wex)    {        using (var stream = wex.Response.GetResponseStream())        using (var reader = new StreamReader(stream))        {            // OpsGenie returns JSON responses for errors            var deserializedResponse = JsonConvert.DeserializeObject<IDictionary<string, object>>(reader.ReadToEnd());            Console.WriteLine(deserializedResponse["error"]);        }    }}