APIs

Contents

In this chapter, you’ll create an API that returns the countries of your site as a CSV file, mount it on the site, and link to it from every page.

This chapter requires the result of chapter 9, as described in Advanced features.

APIs

An API is an HTTP endpoint in your app. It consists of a descriptor and an implementation, placed together in a folder under src/main/resources/apis/.

Unlike a mapping, an API does not pick its own address. Its URL is made from the name of the app and the name of the API, and it can only be reached where it has been mounted.

You have already mounted one. In chapter 7, you added asset to the apis list in the site descriptor. That mounted the API of the Asset library on your site, which is why the URL of your stylesheet contains com.example.tutorial.siteframework:asset.

Task: Create the API

  1. Create the descriptor - Create the file below with the following content:

    src/main/resources/apis/countries/countries.yaml
    kind: "API"
    title: "Countries"
    description: "The countries of the site and their cities, as CSV"
    allow:
      - "role:system.everyone"

    The allow list decides who can call the API. The role system.everyone makes it public.

  2. Create the implementation - Create the file below with the following content:

    src/main/resources/apis/countries/countries.ts
    import type { Content, Response } from '@enonic-types/core';
    
    import { getChildren } from '/lib/xp/content';
    import { getSite } from '/lib/xp/portal';
    
    type City = { photo?: string, slogan?: string, population: number };
    
    export function GET(): Response {
      const children = getChildren({
        key: getSite()!._path,
        count: 100,
      });
    
      const rows = children.hits
        .filter((item) => item.type === `${app.name}:country`)
        .map((country) => {
          const cities = getChildren<Content<City>>({ key: country._path, count: 100 }).hits
            .filter((item) => item.type === `${app.name}:city`);
          const population = cities.reduce((sum, city) => sum + city.data.population, 0);
    
          return [`"${country.displayName.replace(/"/g, '""')}"`, cities.length, population];
        });
    
      return {
        contentType: 'text/csv; charset=utf-8',
        headers: {
          'Content-Disposition': 'attachment; filename="countries.csv"',
        },
        body: [['Country', 'Cities', 'Population'], ...rows].map((row) => row.join(',')).join('\n'),
      };
    }

    For each country, the function counts the cities and adds up their population. The response sets the content type to CSV, and a header that tells the browser to save the result as countries.csv.

  3. Mount the API - In the site descriptor, add countries to the apis list:

    src/main/resources/cms/site.yaml
    apis:
      - "asset"
      - "countries"
  4. Verify the build - The terminal running enonic dev prints BUILD SUCCESSFUL.

  5. Verify the result - Open http://localhost:8080/site/siteframework/master/hello-world/_/com.example.tutorial.siteframework:countries in your browser. It downloads countries.csv, which looks something like this:

    Country,Cities,Population
    "Norway",3,1059779
    "Sweden",1,984748
    "Colombia",3,12072487
    "USA",3,1978100

The API is mounted at the root of the site only. The same address below a country does not exist, and neither does the API on any other site, until an app mounts it there.

The address of an API depends on where it is mounted, so don’t write it by hand. The Portal library creates it for you.

  1. Update the implementation - Replace the content of the page component implementation with the following:

    src/main/resources/cms/pages/hello/hello.ts
    import type { Response } from '@enonic-types/core';
    
    import { assetUrl } from '/lib/enonic/asset';
    import { render } from '/lib/thymeleaf';
    import { apiUrl, getContent } from '/lib/xp/portal';
    
    const VIEW = resolve('./hello.html');
    
    export function GET(): Response {
      const content = getContent()!;
    
      const model = {
        displayName: content.displayName,
        mainRegion: content.page!.regions.main,
        cssUrl: assetUrl({ path: 'styles/main.css' }),
        csvUrl: apiUrl({ api: `${app.name}:countries` }),
      };
    
      return {
        body: render(VIEW, model),
      };
    }

    apiUrl() creates the URL of an API where it is mounted in the current context, here on the site.

  2. Update the view - Replace the content of the page component view with the following:

    src/main/resources/cms/pages/hello/hello.html
    <!DOCTYPE html>
    <html>
      <head>
        <title data-th-text="${displayName}">Sample title</title>
        <link rel="stylesheet" data-th-href="${cssUrl}"/>
      </head>
      <body>
        <header>
          <h1 data-th-text="${displayName}">Sample header</h1>
        </header>
        <main data-portal-region="main">
          <div data-th-each="component : ${mainRegion.components}" data-th-remove="tag">
            <div data-portal-component="${component.path}" data-th-remove="tag"></div>
          </div>
        </main>
        <footer>
          <a data-th-href="${csvUrl}">Countries as CSV</a>
        </footer>
      </body>
    </html>

    The view now has a <footer> with a link to the API.

  3. Verify the result - Open http://localhost:8080/site/siteframework/master/hello-world/norway and click Countries as CSV at the bottom of the page. The browser downloads the file.

When to use an API

An API is the right tool when you decide the URL. When the URL is decided for you, as for llms.txt, use a mapping.

An API is also not tied to the site. The same API can be mounted on other sites, and on the web endpoint of XP, where it is available without a site at all.

Summary

You’ve created an API, mounted it on your site, and used the Portal library to link to it.

For more details, visit the APIs documentation.

Contents

Contents