UmbracoApiController, that you can inherit from that will make building a web API within Umbraco CMS simple. The good thing about this special controller is that it will handle the routing for you. Routing within a CMS can be tricky as a page request does not map to the controller and actions like a normal .NET website. Incoming requests map to virtual pages created within the CMS and stored within a database. Due to this difference, all .NET CMS systems have behind the scenes functionality to enable a request to map to a page in the CMS database.
When using the default routing behaviour of
UmbracoApiController, the API URL will be predetermined. You can override this behaviour, however, I will not show you how to do that here. For reference, to make a custom URL you can add a route in the sites routing table.
Controller: In order to create an API you will need a controller:
The code to create an API is pretty simple. Inherit from
UmbracoApiController, create an action method whose job is to return data back to your webpage. Within your method add the code to get the data and return it!
Being good software developers we should return the API data using a view model. An example of a very basic view model is shown above. Simply get the data, add it to a view model and return it. Dead easy! The next step is to think about the URL, what is the URL? When inheriting from
UmbracoApiController, your API will have a set URL. You can figure out the URL as it will follow this rule:
In this example, the URL will look like this:
fetch API, like this:
async and it uses