Appearance
Backend Templates & Frameworks
Overview
Backend templates provide pre-configured starting points for building server-side applications. Each template includes the necessary tooling, dependencies, and structure to get started quickly with REST API development.
Template Structure
All backend templates follow a consistent structure:
src/- Application source codesrc/lib/- Reusable library code and utilities- Configuration files - Build tools, linting, dependencies
Dockerfile- Container build instructions
The Library
The library contains reusable utilities and services. It provides essential functionality for building backend applications on the platform. The following features are contained within it:
- Helper Services for commonly used Platform Gateway APIs
- Authentication utilities (
fetchAsPrincipal,fetchAsApp) - Error handling and propagation
- Framework-specific utilities
Backend Endpoints
Backend endpoints handle HTTP requests from the frontend and return JSON responses. The templates provide a consistent pattern for defining routes and handling requests.
Creating an Endpoint
Here's an example of a simple GET endpoint that fetches weather data:
ts
app.get("/api/weather/:location", async (req, res, next) => {
try {
const location = req.params.location;
if (!location) {
res.status(400).json({
error: "Missing required parameter: location",
});
return;
}
const weatherData = await WeatherService.getWeatherForecastAsPrincipal(
req,
location,
);
res.json(weatherData);
} catch (error) {
next(error);
}
});py
@app.route("/api/weather/<location>", methods=["GET"])
def get_weather(location: str) -> Response:
"""Retrieve current weather data for a location.
Args:
location (str): Location query used by the weather API.
Returns:
Response: JSON response containing weather data.
"""
weather_data = WeatherService.get_weather_forecast_as_principal(location)
return jsonify(weather_data.to_json())The endpoint receives a location parameter from the URL, calls a service to fetch weather data using fetchAsPrincipal, and returns the result as JSON. Errors are automatically handled by the error middleware.
Error Handling
The backend templates provide automatic error handling for upstream API calls. When an API request to the Platform Gateway fails, errors are automatically caught and forwarded to the frontend with appropriate status codes and headers.
UpstreamHTTPError
The UpstreamHTTPError class captures detailed information about failed HTTP requests, including status codes, headers, and response bodies.
ts
export class UpstreamHTTPError extends Error {
public readonly statusCode: number;
public readonly headers: Record<string, string>;
public readonly body: string;
constructor(
statusCode: number,
message: string = "",
headers: Record<string, string> = {},
body: string = "",
) {
super(message);
this.name = "UpstreamHTTPError";
this.statusCode = statusCode;
this.headers = headers;
this.body = body;
if (Error.captureStackTrace) {
Error.captureStackTrace(this, UpstreamHTTPError);
}
}
}py
class UpstreamHTTPError(Exception):
def __init__(
self,
status_code: int,
message: str = "",
headers: dict[str, Any] | None = None,
body: Any = None,
) -> None:
"""Initialize upstream HTTP error details.
Args:
status_code (int): HTTP status code returned by upstream.
message (str): Human-readable error message.
headers (dict | None): Response headers from upstream.
body (Any): Raw response body content.
"""
super().__init__(message)
self.status_code = status_code
self.message = message
self.headers = headers or {}
self.body = bodyAutomatic Error Handling
The backend templates automatically register error handlers that:
- Catch UpstreamHTTPError instances and forward them to the frontend with the original status code
- Preserve Location headers for authentication redirects (403 responses)
- Handle unexpected errors with a 500 status code
This means you don't need to manually handle errors in your endpoint code - just let exceptions propagate and they'll be handled automatically.
Authentication Flow
When an upstream API call returns a 403 status with a Location header:
- The error handler preserves the
Locationheader in the response - The frontend receives the 403 response with the
Locationheader - The frontend automatically opens an authentication popup
- After successful authentication, the original request is retried
This works seamlessly for both fetchAsPrincipal and fetchAsApp calls.
Template Specific Information
Express Template - TypeScript-based backend using Express.js
Python Template - Python-based backend using Flask