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
- Authentication Header
The method expects an access token and adds it as aBearertoken in theAuthorizationheader. This ensures secure calls to the REST API.http.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken); - Filtering by Field
The method builds a query string using the$filteroperator, 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 - Limiting Results
Using$top=1, only the first matching item is returned. This reduces payload size and improves performance. - 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}"); - Parsing JSON Response
The method parses the response into aJsonDocument. If no items are found, it returnsnull. 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
$selectclause 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
| Aspect | Explanation |
|---|---|
| Purpose | Retrieve the first list item matching a field value |
| Input Parameters | Site URL, List name, Field name, Field value, Access token |
| REST Query | Uses $filter, $select, and $top=1 for optimized queries |
| Authentication | Bearer token via Authorization header |
| Return Type | JsonElement? (null if no results found) |
| Error Handling | Throws exception with HTTP status and response body if request fails |
| Enhancements | Multi-condition filters, richer field selection, logging integration |
