Kirkbride Solutions

OData V4 Api How To Filter And Select With Multiple Expands

tutorial

Open Data Protocol (OData) is a very powerful way to create reusable API's for multiple clients. More information on OData can be found at the official site here.

The feature I care most about when using Odata is the ability to expose one endpoint that multiple customers can consume by receiving only the things that they care about or need. To meet this end we (or the customer) will generally create Odata queries. Since these queries leverage their own syntax and are not always the most intuitive (especially if you're newer to writing them) I figured I would go ahead and do a quick sample of one particular case I ran into.

The scenario in question is when you need to:

  1. Return a specific record
  2. Expand two segments
  3. Perform select for specific data elements on each
  4. Filter the results of the first segment based on a known value

To demonstrate how to do this I'll be using the Odata api that is built by following along with Kevin Dockx' course on Pluralsight titled "Building a Consistent RESTful API with OData V4 in ASP.NET".

http://localhost:5810/odata/People(1)?$expand=VinylRecords($filter=Artist eq 'Beatles';$select=Title,Year),Friends($select=Email)

This should seem pretty straight forward, and this will return the following result:

VS Create a new project

We are opting into receive the VinylRecords and Friends objects by specifying them in the Expand portion of the query. We Filter the vinyl records to return only the results that meet our criteria, and then select only the Title and Year. Additionally we select only the email property from the Friends object.