Tomas
Tomas

Reputation: 18117

OData navigation use $expand instead of url /path

I just started using OData and implementing it into my c# Web API project. The one thing which bothers me is that to load navigation property the $expand query is used instead of url /path.

For example, by rest api specification if we want to load entity with navigation table(parent->child) we usually call

/users/1/logs

result

{
"Id": 12254,
"ApiKey": 104254635,
"FirstName": "Joshua",
"LastName": "Marcus",
"DateStamp": "2019-06-11T06:43:11.897+03:00",
"TimeZone": "UTC",
"Logs":[
{"Id": 74216060, "Result": true, "DateStamp": "2019-06-11T06:51:17.487+03:00", "ConversionTime": 3,…},
{"Id": 74215748, "Result": false, "DateStamp": "2019-06-11T06:50:11.117+03:00", "ConversionTime": 3,…}
]
}

The OData to load navigation property use query parameters instead

/users/1?$expand=logs

That's a little bit weird and looks out of Rest API specification to query resources like this. Maybe someone could comment on this and give more information about why such a solution is used in OData and is it possible to use a common parent/child structure to query related records using OData?

Upvotes: 0

Views: 1372

Answers (1)

Dirk Trilsbeek
Dirk Trilsbeek

Reputation: 6023

The option $expand only tells the service to return your navigation elements inline with the result for your request to the parent entity. You should be able to access the logs entity set with your url /users/1/logs, and generally it should return an array of log entities, but without the parent entity properties. But if you want both your parent entity and the (expanded) logs in one request and result, you need to use the $expand option. Think of it as a way to reduce the number of queries when fetching hierarchical data sets. With $expand you can also decide which child navigation properties to expand (and to which level).

With this OData v2 test service you can for instance request a Product entity and use the $expand option to not just expand the Supplier, but all the products of the Supplier:

base url for the service: https://services.odata.org/V2/(S(readwrite))/OData/OData.svc/ (the service replaces part of its url with a randomized string, so you'll see a slightly modified version of this url once you open the base url in a browser).

and with the request to Products(0)?$expand=Supplier/Products you'll get the product with Id 0, its supplier inline with the product, and all products of the supplier inline with the supplier. If you however request Products(0)/Supplier/Products, you will only receive an array of product entities without the supplier data or properties of the product you initially requested (although it is also included in the list in this case).

Upvotes: 1

Related Questions