Search code examples
c#jsonrestsharppostmark

"{\"ErrorCode\":402,\"Message\":\"Received invalid JSON input.\"}" When trying to call restsharp to make call to Postmark


i'm trying to make a call to Postmarks email service RestAPI using restsharp in C# and get a "{\"ErrorCode\":402,\"Message\":\"Received invalid JSON input.\"}" error every time i send it even though i have set the data format to json, i have even tried a custom json serialize . im not sure if im setting up the Parameters properly or even it this is the best way to achieve what i'm trying so any help and suggestions would be welcome.

public void SendRest(string emailAddress, string subject, string body, params string[] recipients)
    {
        var recipientString = "";
        foreach (var recipient in recipients)
        {
            recipientString = recipientString + recipient + ',';
        }

        var client = new RestClient();
        client.BaseUrl = new Uri("https://api.postmarkapp.com/email");

        var request = new RestRequest(Method.POST);
        request.RequestFormat = DataFormat.Json;
        request.AddHeader("Content-Type", "application/json");
        request.AddHeader("Accept", "application/json");
        request.AddHeader("X-Postmark-Server-Token", "Valid-Token");

        request.AddParameter("From", "test@testington.co.uk");
        request.AddParameter("To", "robin.windon@hotmail.co.uk");
        request.AddParameter("Subject", "hi");
        request.AddParameter("TextBody", "this is a test");
        request.AddParameter("TrackOpens", true);
        request.AddParameter("TrackLinks", "None");


        IRestResponse response = client.Execute(request);
    }

Solution

  • You are sending the parameters either as (serialized) POST parameters (in the body) or GET-parameters, I am not sure how restsharp does handle this.

    But you are not sending any JSON in the POST body as required.

    Should be something like this I guess:

    var params = JSON.Stringify(
        {
            "From": "robin.windon...",
            "To": "",
            "Subject": "",
            "TextBody": "",
            "TrackOpens": "",
            "TrackLinks": ""
        }
    );
    request.AddParameter("application/json", params, ParameterType.RequestBody);