Search code examples
c#restapirestsharp

Restsharp: Automatically map query parameters


I have a class Endpoints.cs which contains all GET and POST endpoints I use with my REST server.

I have made a generic GET method in my APIHelper class:

public static T Get<T>(string endpoint, string[] qArgs) where T : new()
        {
            RestRequest request = new RestRequest(endpoint);
            var response = client.Get<T>(request);
            return (T)response.Data;
        }

Now, some of my endpoints contain query parameters. How do I modify the method so it automatically reads qArgs and applies them to the endpoint with .AddUrlSegment? Ofc, I don't know which endpoint will end up in Get(), so the method should somehow know which urlsegment to map with that particular value.

I'm using Restsharp and Newtonsoft.json.


Solution

  • Just having a list of parameters is not enough since you need to know parameter names.

    RestSharp supports adding query parameters without specifying them in the request URL, you only need parameter names in {} when using URL segment parameters. If you accept this default, you can do what you want.

    public static T Get<T>(string endpoint, params KeyValuePair[] parameters) where T : new()
    {
        var request = new RestRequest(endpoint);
    
        foreach (var parameter in parameters)
        {
            if (endpoint.Contains($"{{{parameter.Key}}}")
                request.AddUrlSegmentParameter(parameter.Key, parameter.Value);
            else
                request.AddQueryStringParameter(parameter.Key, parameter.Value);
        }
        var response = client.Get<T>(request);
        return response.Data;
    }
    

    So when you call

    Get<Blah>(
        "/something/{id}", 
        new KeyValuePair("id", "123"),
        new KeyValuePair("sort", "asc")
    );
    

    It will send your request to http://baseurl/something/123?sort=asc