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.

A diagram of PHP objects becoming a multipart POST of article.json, metadata and an image, signed with HHMAC, and sent to Apple News. A diagram of PHP objects becoming a multipart POST of article.json, metadata and an image, signed with HHMAC, and sent to Apple News.

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

All writing about Apple News API

Featured projects

All projects

More writing

All writing