Deserializing JSON response using RestSharp

Iā€™m looking for some general advice with an API framework I am setting up using C# and RestSharp as the client library. Iā€™ve successfully set up an initial test, but Iā€™m now looking at creating a series of assertions to ensure that certain values are returned in the response

My test looks as below:

        [Test]
    public void ShouldHaveDataAttributes()
    {
        var restClient = new RestClient("http://ergast.com/api/f1");

        var restRequest = new RestRequest("2016/circuits.json", Method.GET);

        var restResponse = restClient.Execute(restRequest);

        dynamic jsonResponse = JsonConvert.DeserializeObject(restResponse.Content);

        dynamic jsonObject = jsonResponse.MRData.CircuitTable;
        int circuitId = (int)jsonObject.season;
        System.Console.WriteLine(jsonObject);
    }

The jsonObject returns the below data:

{ ā€œseasonā€: ā€œ2016ā€, ā€œCircuitsā€: [ { ā€œcircuitIdā€: ā€œalbert_parkā€, ā€œurlā€: ā€œAlbert Park Circuit - Wikipediaā€, ā€œcircuitNameā€: ā€œAlbert Park Grand Prix Circuitā€, ā€œLocationā€: { ā€œlatā€: ā€œ-37.8497ā€, ā€œlongā€: ā€œ144.968ā€, ā€œlocalityā€: ā€œMelbourneā€, ā€œcountryā€: ā€œAustraliaā€ } }] }

My question is how would I specifically check that, for example the correct ā€œcircuitIdā€ is returned or that the ā€œcircuitNameā€ value is ā€œAlbert Parkā€? Iā€™m keen to carry on utilising RestSharp for my framework so was hoping there was an extension to allow me to do that

Morning Andrew,

If you add a reference in to your test project for ā€˜Newtonsoft.Json.Linq;ā€™ then the below snippet Iā€™ve tested and would allow you to extract out values from your response.

    var returnedJson =
            "{ \"season\": \"2016\", \r\n\"Circuits\": [ { \"circuitId\": \"albert_park\", \"url\": \"http://en.wikipedia.org/wiki/Melbourne_Grand_Prix_Circuit\", \"circuitName\": \"Albert Park Grand Prix Circuit\", \"Location\": { \"lat\": \"-37.8497\", \"long\": \"144.968\", \"locality\": \"Melbourne\", \"country\": \"Australia\" } }] }"; // I've escaped the response but you would just set the returnedJson to the response you get back

        // parse the json response so that we can get at the key/value pairs
        dynamic api = JObject.Parse(returnedJson);

        // grab the values and do your assertions :-)
        var season = api.season;
        var circuits = api.Circuits;
        var circuitId = api.Circuits[0].circuitId;
        var circuitName = api.Circuits[0].circuitName;

Hope the above helps,

Viv

1 Like

This is brilliant thanks Viv!

The slight issue I have is that the returnedJson variable is pretty big as there are 21 different circuits being returned in the response. Would there be an alternative way that I could return the data?

1 Like

Do you need to check each circuit?

Depending on what you want to check you couldā€¦

  • Count on the number of circuits returned to see if that matches the expected number?
  • Get Circuits[0], Circuits[1], Circuits[2] etc but there would be lots of checks?
1 Like

just managed to figure it out as you replied to me, thanks Viv! In reality, Iā€™ll only be asserting against a small amount of data coming back so have come up with a solution.

In general, for API testing Iā€™m struggling to figure out what assertions need to be done? Are there certain assertions that you should run every time(e.g. that the appropriate status code comes back)? Other assertions, I assume, would be based on the data that has been consumed and the values we are expecting to be returned?

Iā€™ve come from a background of UI automation and whilst I am a firm believer in testing at the API layer where we can, Iā€™m finding it a bit of a mindshift to get used to :slight_smile:

As a general bit of advice, when coming up with an API framework I am looking at writing this in C# as it makes sense to utilise the same programming language that the company Iā€™m working at use. Something Iā€™m trying to work out is why weā€™d write an API test framework in code(be it using c# and RestSharp or Java and RestAssured), as opposed to setting a framework up in Postman or SoapUI. What would be the proā€™s and conā€™s of each?

@vivrichards Iā€™ve logged a separate post for my other question so that itā€™s separated

1 Like

Hello Andrew,
in our project, we use RestSharp for API testing. Our approach is to specify the type of returned response for the service, it allows to get the class or collection of known type instead of dynamic.
Then we just generate the expected outcome object in test and compare it to the object we received in response. For objects comparison, we use CompareNETObjects package by KellermanSoftware.

So the test looks like:

    [Test]
    public void Segment_Get_AnyActiveSegment()
    {
        MarketingSegment segment = // here we request test data from SQL DB
        Ensure.Found(segment, Is.Not.Null, "Couldn't find a segment for the test.");

       // Inside the following method via some wrapper we call restClient.Execute<MarketingSegmentDto>(JsonRequest)
        IRestResponse<MarketingSegmentDto> getRequestResult = Steps.GetMarketingSegmentRequestStep.SendRequest(segment.Id);

        ServiceResponseValidation.ValidateOkResponse(getRequestResult);

        Steps.EntityModificationValidator.ValidateEntityNotChanged(expected: new MarketingSegmentDto(segment), actual: getRequestResult.Data);
    }

Hope it was helpful :slight_smile:

1 Like