In this tutorial, you will learn how to create a very simple JSON API using Umbraco 8. Returning JSON is pretty much the standard way of returning data from an API. It is no-surprised then that Umbraco comes with helpers to enabled this functionality. I will detail all the steps that you will need to follow in order to create an API within Umbraco V8. You will also learn about how URLs work within Umbraco and how this affects the URL for your end-points.
How To Create An API Within Umbraco
To create a JSON API you will need to use two main components:
The good thing about inheriting from the Umbraco API controller is that you will not have to worry about configuring any routing up. Umbraco will handle this for you. The easiest way to return JSON from within a controller is to use the MVC action result, JsonResult. Let us start with a simple example, assuming you had this view model:
You could build an API and return the data located inside of this class as JSON like this:
What's My Umbraco API Url?
Determining the URL for this API is simple. If you inherit from
UmbracoApiController the start of your API URL will be
/Umbraco/Api/. The second part of the URL will be determined by the name of your controller and its action:
If 'MyApi' is the name of the controller and 'GetJson' is the name of the action method, the API URL will be:
Another thing to keep in mind is that by default the request type will need to be 'GET' request, otherwise, a 404 will be thrown when you try to access it. If you want to learn more about web API within Umbraco, you can learn more here. Happy Coding!