In this tutorial, you will learn how to create an API within Umbraco V7 and consume that data using plain old Javascript. If you're new to using Web API within Umbraco, I suggest you read, How To Create A Web API In Umbraco In Less Than 5 Minutes!. The gist of that article is that Umbraco provides a special controller, 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:

Next, you will need some Javascript to call the API. For this we can use the fetch API, like this:

This code uses fetch to get the data. Notice this JavaSCript method is async and it uses await. As you can see getting your head around how to call content from a web API written in Umbraco is exactly the same as a normal API. The challenge is knowing the correct URL to use! If you are new to JavaScript then I recommend that you buy and read, Javascript the Definitive Guide. Happy Coding 🤘