Skip to content
Greg Bowler edited this page May 18, 2026 · 3 revisions

WebEngine can serve structured responses as well as HTML pages. That means one application can provide normal pages for the browser and API endpoints for background requests or other consumers.

HTML pages vs API endpoints

The important difference is not that the application has changed, but that the response type has changed. HTML routes build a document for the browser. API routes build structured data, usually JSON.

WebEngine keeps those routes within the same overall routing model, so the project does not need a completely different way of thinking about requests just because one endpoint returns data instead of a page.

Compare API logic to page logic:

use GT\Json\Schema\JSONDocument;

function go(JSONDocument $document):void {
	$document->set("name.first", "Ada");
	$document->set("name.last", "Lovelace");
}

Instead of HTML, API views can be built up completely dynamically from PHP (using the JSONDocument), or it can be based on a .jsonschema file to provide defaults and inbuilt schema validation:

{
	"$schema": "https://json-schema.org/draft/2020-12/schema",
	"type": "object",
	"oneOf": [
		{
			"$ref": "#/$defs/request"
		},
		{
			"$ref": "#/$defs/response"
		}
	],
	"$defs": {
		"request": {
		},
		"response": {
			"type": "object",
			"required": [
				"name"
			],
			"properties": {
				"name": {
					"type": "object",
					"required": [
						"first",
						"last"
					],
					
					"properties": {
						"first": {
							"type": "string"	
						},
						"last": {
							"type": "string"
						}						
					}
				}
			}
		}
	}
}

Unlike with page views, API views don't require a view model - the JSON is optional, allowing an API response to be completely built dynamically in PHP. The JSON is there for when it helps with scalability and maintainability.

What API logic looks like

API logic feels very similar to page logic. It still receives the request, can still use the same service container, and can still call the same application classes.

The main difference is the view model. HTML responses work with an HTMLDocument. API responses usually work with a JSONDocument, which is part of the JSON package documented at https://www.php.gt/docs/Json/Home/.

For many page interactions, there is no need to build a separate API endpoint at all. A server-rendered HTML application can still achieve a more fluid browser experience without switching every background interaction to a JSON API. That topic comes later in fluid user experience.


Next up, let's learn about how WebEngine handles configuration.

Clone this wiki locally