Orchard Core simplifies creating API endpoints by leveraging ASP.NET Core's MVC framework. We can define a controller with specific methods, and Orchard Core will automatically expose those as endpoints.
Let's start a simple controller in the CMS core project with the following code.
using Microsoft.AspNetCore.Mvc;
namespace OCBC.HeadlessCMS.Controllers;
[ApiController]
[Route("api/v1/product")]
public class ProductController : Controller
{
[HttpGet("product-info")]
public IActionResult GetProductInformation()
{
return Ok(new { message = "Hello from Orchard Core!" });
}
}
We should be seeing the message being printed when we visit the endpoint.
Since we are building this serving API, so we need a way to retrieve the content items from Orchard Core. In Orchard Core, we can use IOrchardHelper in to interact with content items and other Orchard Core services easily. IOrchardHelper provides utility methods to retrieve content items, execute queries, and work with shapes, making it incredibly useful for API development.
There are a few key methods in IOrchardHelper, as explained in the following table.
For example, to retrieve all the published product information with "ProductInformation" as the ContentType, we will need to make use of the QueryContentItemsAsync, as demonstrated below.
using Microsoft.AspNetCore.Mvc;
using OrchardCore;
namespace OCBC.HeadlessCMS.Controllers;
[ApiController]
[Route("api/v1/product")]
public class ProductController(IOrchardHelper orchard) : Controller
{
[HttpGet("product-info")]
public async Task<IActionResult> GetProductInformation()
{
var productInformation = await orchard.QueryContentItemsAsync(q =>
q.Where(c => c.ContentType == "ProductInformation"));
return Ok(productInformation);
}
}
With this, the output of the endpoint should be a JSON as follows.