When integrating applications with enterprise content platforms, it is common to query items in lists by a specific field value. Instead of retrieving all items and filtering locally, a more efficient approach is to call the platform’s REST API directly with a filter query.


Building a Helper Method to Query List Items via REST API

When integrating applications with enterprise content platforms, it is common to query items in lists by a specific field value. Instead of retrieving all items and filtering locally, a more efficient approach is to call the platform’s REST API directly with a filter query.

This article explains a reusable helper method in C# that retrieves the first item in a list by a given field value, returning the result as a JsonElement. This is particularly useful in scenarios where only one record is needed, such as validating if an item already exists before inserting new data.


Code Walkthrough

private static async Task<JsonElement?> GetFirstItemByFieldAsync(
    string siteUrl,
    string listName,
    string fieldName,
    string fieldValue,
    string accessToken)
{
    using var http = new HttpClient();
    http.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
    http.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

    string escapedValue = fieldValue.Replace("'", "''");
    string endpoint =
        $"{TrimEndSlash(siteUrl)}/_api/web/lists/getbytitle('{Uri.EscapeDataString(listName)}')" +
        $"/items?$filter={fieldName} eq '{escapedValue}'&$select=Id,{fieldName}&$top=1";

    var res = await http.GetAsync(endpoint);
    var body = await res.Content.ReadAsStringAsync();

    if (!res.IsSuccessStatusCode)
        throw new Exception($"Error {(int)res.StatusCode}: {res.ReasonPhrase}\n{body}");

    using var doc = JsonDocument.Parse(body);
    if (!doc.RootElement.TryGetProperty("value", out var arr) || arr.GetArrayLength() == 0)
        return null;

    return arr[0].Clone();
}


Key Implementation Details

  1. Authentication Header
    The method expects an access token and adds it as a Bearer token in the Authorization header. This ensures secure calls to the REST API. http.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
  2. Filtering by Field
    The method builds a query string using the $filter operator, targeting a specific field. To prevent syntax issues, single quotes inside the field value are escaped. string escapedValue = fieldValue.Replace("'", "''"); The resulting REST query looks like: /_api/web/lists/getbytitle('ListName')/items?$filter=FieldName eq 'Value'&$select=Id,FieldName&$top=1
  3. Limiting Results
    Using $top=1, only the first matching item is returned. This reduces payload size and improves performance.
  4. Error Handling
    If the response status is not successful, an exception is thrown with detailed information: if (!res.IsSuccessStatusCode) throw new Exception($"Error {(int)res.StatusCode}: {res.ReasonPhrase}\n{body}");
  5. Parsing JSON Response
    The method parses the response into a JsonDocument. If no items are found, it returns null. Otherwise, it clones the first array element. if (!doc.RootElement.TryGetProperty("value", out var arr) || arr.GetArrayLength() == 0) return null; return arr[0].Clone();

Advantages of This Approach

  • Efficiency: Queries only one item instead of fetching the entire list.
  • Security: Uses OAuth tokens for API access.
  • Flexibility: Works with any list and any field by passing parameters.
  • Error Transparency: Returns clear exception messages when the API call fails.

Possible Enhancements

  • Add support for multiple filter conditions.
  • Extend the $select clause to return more fields.
  • Introduce logging for tracing API calls and debugging.
  • Wrap this method into a generic data access service for better reusability.

Summary Table

AspectExplanation
PurposeRetrieve the first list item matching a field value
Input ParametersSite URL, List name, Field name, Field value, Access token
REST QueryUses $filter, $select, and $top=1 for optimized queries
AuthenticationBearer token via Authorization header
Return TypeJsonElement? (null if no results found)
Error HandlingThrows exception with HTTP status and response body if request fails
EnhancementsMulti-condition filters, richer field selection, logging integration

References for Further Reading

Edvaldo Guimrães Filho Avatar

Published by