Publishing to Apple News from PHP
Apple News needs every request signed and a strict JSON format exactly right, and my PHP library does both.
Apple News has two halves: the Apple News Publisher API, an HTTP API with its own request signing, and Apple News Format, or ANF, the JSON document that describes an article’s components, styles and layout. I wrote my Apple News API library so a PHP publishing system can publish without anyone hand-writing that JSON. It signs every request and models more than 45 component types as PHP objects.
Signing requests
The API doesn’t use OAuth or a bearer token. Each request carries an Authorization header signed with HMAC-SHA256, using a key ID and a secret from your Apple News channel.
You sign the HTTP method, the full URL and the current UTC date, concatenated with no separator, and for a POST the content type and the whole body go on the end. The secret arrives base64-encoded and has to be decoded first; the signature is base64-encoded again:
$canonical = $method . $url . $date;
if ($method === 'POST' && $contentType !== null && $body !== null) {
$canonical .= $contentType . $body;
}
$signature = base64_encode(hash_hmac('sha256', $canonical, base64_decode($secret, true), true));
$header = sprintf('HHMAC; key=%s; signature=%s; date=%s', $keyId, $signature, $date);
The body you sign has to be byte for byte the body you send, multipart boundaries included. I decode the secret in strict mode, so one that isn’t valid base64 throws straight away.
Uploading an article
Creating an article is a multipart/form-data POST to the channel: an article.json part, an optional metadata part wrapped in a data key, and one part for each image the article refers to with a bundle:// URL. The client builds the body; you pass a map of bundle names to local files:
$article->addComponent(Photo::fromBundle('hero.jpg'));
$client->createArticle($channelId, $article, null, [
'bundle://hero.jpg' => '/path/to/hero.jpg',
]);
Updating needs the article’s current revision token from the last response, which the client adds to the metadata part, and the call becomes updateArticle($articleId, $revision, $article). If the article has changed since, Apple answers with a 409 conflict, and you fetch a fresh revision and retry.
Building the document
ANF documents get big: dozens of component types, named text styles, component styles, layouts, animations and conditional rules for dark mode or narrow screens. The library models all of it as PHP objects with a fluent interface:
$article = Article::create(identifier: 'story-123', title: 'A headline', language: 'en');
$article
->addComponent(new Title('A headline'))
->addComponent(new Heading('Background', level: 2))
->addComponent((new Body('The <strong>first</strong> paragraph.'))->setFormat('html'));
Each object knows its own ANF role and serialises itself. The article collects them, along with its styles and metadata, into the final document.
Empty objects
Any strict JSON API trips over one PHP habit. PHP has one array type for lists and maps, and json_encode([]) produces []. But in ANF an empty layout or style is an object, and Apple expects {}. Send [] and the document is invalid.
The library walks the finished data and swaps every empty array for an empty stdClass, which encodes as {}:
private static function convertEmptyArraysToObjects(mixed $data): mixed
{
if (is_array($data)) {
if (empty($data)) {
return new \stdClass();
}
return array_map(self::convertEmptyArraysToObjects(...), $data);
}
return $data;
}
When Apple says no
Apple’s error responses are specific, naming the problem and the field: an error code such as INVALID_DOCUMENT and a key path such as components[0].text. The library turns them into an AppleNewsException with getErrorCode() and getKeyPath(), and a separate AuthenticationException for 401 and 403.
Bring your own HTTP client
The library doesn’t ship an HTTP client. It depends on the PSR-18 client and PSR-17 factory interfaces, so Guzzle, Symfony’s client or whatever your application already uses will do, and there’s no framework dependency. It needs PHP 8.1 or later, and every class is in the documentation.
composer require tomgould/apple-news-api guzzlehttp/guzzle guzzlehttp/psr7
More on Apple News API
Featured projects
-
GitHub Auditor
Health, access and activity reports for more GitHub and Bitbucket repositories than you can keep in your head.
-
PrintMD
Markdown in, and a designed PDF, Word or PowerPoint file out. Its PDF service runs on your own computer.
-
Where Should I Live
Which city would leave you best off? Cities ranked by take-home pay, living costs, visas and the way you live.
-
Solar Calendar
Thirteen months of exactly four weeks, with the year starting on the first Monday on or after the spring equinox.
-
TurboPush
Resumable uploads of very large files from the browser, put back together by one PHP class on the server.
More writing
-
Many sessions at once, and what still needs me
Fifteen coding-agent sessions across two Linux boxes, one session that watches the rest, what it may answer for me, what it never may, and why a yes it passes on gets checked against what I typed.
-
61 public repos of agent tooling, none installed, six ideas kept
One author, 61 public repositories of coding-agent tooling: what I checked before any of it got near my Linux boxes, why none of it was installed, and the six ideas I built my own way.
-
Rules a coding agent cannot talk its way round
The hook that reads every command a coding agent wants to run on my Linux boxes: what it refuses, the 27 proofs that its tests fail when a rule is taken out, and the four lines every report opens with.
-
Dozens of repos, one person
46 repositories and two Linux boxes with nobody else on them: the diary, the decision table, the rebuild guide and the job that keeps both sets of clones in step.