Link helper

The Web SDK has a link helper to build and parse REST API links (URLs).

This article only covers one example, but it is similar for all links. See the API docs for a complete overview.

First shown is how link parsing and building works, followed by how the link helper can help with that.

Link objects represent a link to a resource using the Hypertext Application Language (HAL) format.

Links can be templated, which means they contain variables that need to be bound before the link is useful. For example, the Link object that is a template to a entity looks like this:

RequestResponse
Template = true
Title = "Get the entity with the specified id"
Uri = "http://localhost:8080/api/entities/{id}{?culture,members,groups,renditions,nestedRelations,loadPermissions}"

This template can be fetched like this:

RequestResponse
ApiRoutesDictionary routes = await MClient.Api.GetApiRoutesAsync();
Link entityByIdTemplate = routes[Constants.Api.EntityById.TemplateName];

Where Constants.Api.EntityById.TemplateName is just "entity_by_id".

To get a link to a specific link, like with id 1000, the variable needs to be filled in:

RequestResponse
var mappings = new Dictionary<string, string> { { Constants.Api.EntityById.Id, "1000" } };
string assetUrl = entityByIdTemplate.Bind(mappings);

The dictionary links the variable names to the values. The Bind method will replace the variables with the values in the link and remove optional arguments that were not specified.

This will result in the following URL (as string): "http://localhost:8080/api/entities/1000".

The Bind method can be imported from Stylelabs.M.Sdk.WebApiClient.Utilities.

Parsing the URL we just created, can be done by using the GetVariableValue method of the Uri class. This also needs the Link template from before. The result of this method will be "1000", which matches what was filled in by the previous section.

RequestResponse
string assetId = new Uri(assetUrl).GetVariableValue(entityByIdTemplate, Constants.Api.EntityById.Id);

Manually parsing and building links can be tedious, so it is best to leave it to the link helper.

The following snippet constructs a link object to the entity with id 1000.

RequestResponse
Link entityLink = await MClient.LinkHelper.EntityToLinkAsync(1000);

If the Web SDK is connected to http://localhost:8080, then entityLink.Uri will point to http://localhost:8080/api/entities/1000.

If only the entity id is to be returned from an entity link, then use the following snippet:

RequestResponse
long? entityId = await MClient.LinkHelper.IdFromEntityAsync(entityLink);

If passing the link that was created earlier, then the result will be 1000.

Do you have some feedback for us?

If you have suggestions for improving this article,