Skip to content

Backend API Access Patterns

The backend templates provide utilities for making authenticated API calls to the Platform Gateway. There are two main approaches depending on the authentication context needed.

Fetch as Principal

Use fetchAsPrincipal function when you need to make API calls on behalf of the authenticated user. This function automatically forwards the user's authentication token from the incoming request.

ts
static async getWeatherForecastAsPrincipal(
  req: express.Request,
  location: string,
): Promise<WeatherData> {
  const path = `/api/gw/weather/current.json?q=${location}`;
  const response = await fetchAsPrincipal(req, path);

  if (!response.ok) {
    throw new Error(
      `Failed to fetch weather data: ${response.status} ${response.statusText}`,
    );
  }

  const data = (await response.json()) as WeatherData;
  return data;
}
py
@staticmethod
def get_weather_forecast_as_principal(location: str) -> WeatherResponse:
    """Fetch current weather forecast data.
    Args:
        location (str): Location query string (e.g., "London").
    Returns:
        WeatherResponse: Validated weather data.
    """
    response = fetch_as_principal(URL.format(location=location))
    return WeatherResponse.from_json(response.json())

When to use:

  • Accessing user-specific data
  • Performing actions on behalf of the user
  • When the API requires user-level permissions

Fetch as App

Use fetchAsApp when you need to make API calls with application-level permissions. This function uses the application's authentication token.

ts
static async getWeatherForecastAsApp(location: string): Promise<WeatherData> {
  const path = `/api/gw/weather/current.json?q=${location}`;
  const response = await fetchAsApp(path);

  if (!response.ok) {
    throw new Error(
      `Failed to fetch weather data: ${response.status} ${response.statusText}`,
    );
  }

  const data = (await response.json()) as WeatherData;
  return data;
}
py
@staticmethod
def get_weather_forecast_as_app(location: str):
    """Fetch current weather forecast data.
    Args:
        location (str): Location query string (e.g., "London").
    Returns:
        WeatherResponse: Validated weather data.
    """
    response = fetch_as_app(URL.format(location=location))
    return WeatherResponse.from_json(response.json())

When to use:

  • Accessing shared application data
  • Background tasks not tied to a specific user
  • When the API requires application-level permissions

Authentication

Both approaches automatically handle authentication:

  • fetchAsPrincipal: Uses the Authorization header from the incoming HTTP request
  • fetchAsApp: Uses the APP_BACKEND_APP_TOKEN environment variable

If an API call fails with a 403 status and includes a Location header, the error is automatically propagated to the frontend, which will trigger the authentication flow.