An API response is not an Entity: designing an article card

An independent Symfony example separates an API article card from its internal record: explicit DTO fields, a mapper, locale, null and time format. A fixture and tests describe the contract.

A separate card with selected elements represents an explicit public contract.
A separate card with selected elements represents an explicit public contract.

This API endpoint reads a synthetic fixture, so it needs neither an ORM nor a real article database. In the shared article_demo, the note store uses MySQL 8.4/InnoDB through native PDO; the API exercise neither replaces nor accesses it. The DTO, mapper and new route coexist with earlier routes.

A page listing articles needs a small card: a title, a short description, a language and a publication date. Inside the application, the same content may have editorial notes, a local row number, an editing state and a relationship to its owner. Building the external response from the entire internal record allows storage changes to alter the client contract without an explicit decision.

The article about Admin, Frontend and API considered the responsibilities of different applications. Here we will define a concrete API result: an article card with an explicit set of fields. We will build an independent Symfony example in which adding an internal field must not change the JSON. This is new teaching code with fictional data, without working Entity classes or private bundles.

Start with the agreement made to the data consumer

The client receives one card in a particular language. I choose the following contract for this example:

Field Type and meaning What it does not mean
contentId A nonempty string identifying the content consistently A local database row number
locale One of uk, ru or en A language guessed from the title
title The nonempty title of the selected translation Every translation at once
summary A nonempty description or null An empty string standing in for a missing description
publishedAt A UTC time, to the second, ending in Z The time of the latest request or edit

All five fields are always present. An unavailable summary is represented by null, not an omitted key. That lets the client distinguish an intentionally absent value from an accidentally incomplete response. The field set and time precision are decisions made for this example; Symfony does not require this particular card.

Save the fixture and schema files from the next two blocks relative to the root of the existing article_demo, created in the first article. First, let us define their contents.

Save the expected document as tests/Fixtures/article-card.en.json. The date and values are fictional lab data, not information about an actual publication:

{
  "contentId": "article-demo-a",
  "locale": "en",
  "title": "Local backups",
  "summary": "A teaching article card.",
  "publishedAt": "2000-01-02T03:04:05Z"
}

This fixture provides an independent reference for regression comparisons. When the server code changes, a test should detect an extra field, a missing required key or a changed type. Updating the reference solely to remove a test failure would silently approve a new contract.

The schema describes the shape; code creates the response

Create contract/article-card.schema.json:

{
  "$schema": "https://json-schema.org/draft/2020-12/schema",
  "title": "Teaching ArticleCard response",
  "type": "object",
  "additionalProperties": false,
  "required": [
    "contentId",
    "locale",
    "title",
    "summary",
    "publishedAt"
  ],
  "properties": {
    "contentId": {
      "type": "string",
      "minLength": 1
    },
    "locale": {
      "type": "string",
      "enum": [
        "uk",
        "ru",
        "en"
      ]
    },
    "title": {
      "type": "string",
      "minLength": 1
    },
    "summary": {
      "type": [
        "string",
        "null"
      ],
      "minLength": 1
    },
    "publishedAt": {
      "type": "string",
      "format": "date-time",
      "pattern": "^[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}Z$"
    }
  }
}

The JSON Schema object reference separately defines allowed properties, required keys and additional fields. In our schema, additionalProperties: false specifies a closed set. The file itself validates nothing during an HTTP request: this lab does not install a JSON Schema validator. The tests below compare the result with an exact fixture, while the schema provides a readable formal description of the agreement.

The word DTO does not add protection by itself. A data transfer object is useful when its fields, types and transformation are explicit. If a DTO retains the entire Entity and then hands it to a serializer, the external contract still lacks a meaningful boundary.

A card does not need to contain everything an interface might want someday. A cover image, for example, would require an agreement about its address, alternative text and missing-image behaviour. An author link would require a definition of the author's public identity. We do not add those fields preemptively, because that would make promises without explaining their rules. First define a specific client scenario and the result it needs.

An incoming command to edit content would have a different shape as well. Convenient input fields in an editor do not determine what can be returned to a visitor. Using one class in both directions quickly obscures which values come from the client, which are calculated by the server and which are allowed in a particular response. In this exercise, the DTO describes only the outgoing card.

The next step in the shared project

We continue one teaching Symfony project, article_demo, independent of the private platform. We create it once in the first article; later steps add capabilities to the same application. All paths below are relative to the article_demo root.

php --version
composer --version
composer require --dev symfony/test-pack --no-interaction
mkdir -p src/Api src/Catalogue src/Controller contract tests/Fixtures tests/Unit

The internal record deliberately contains more

The file src/Catalogue/FixtureArticleCatalog.php contains a synthetic catalogue:

<?php

declare(strict_types=1);

namespace App\Catalogue;

final class FixtureArticleCatalog
{
    public function find(string $contentId): ?array
    {
        if (!in_array($contentId, ['article-demo-a', 'article-demo-draft'], true)) {
            return null;
        }

        return [
            'databaseId' => 73,
            'contentId' => $contentId,
            'publicationState' => $contentId === 'article-demo-a' ? 'published' : 'draft',
            'publishedAt' => new \DateTimeImmutable('2000-01-02T05:04:05+02:00'),
            'translations' => [
                'uk' => ['title' => 'Локальні резервні копії', 'summary' => 'Навчальна картка матеріалу.'],
                'ru' => ['title' => 'Локальные резервные копии', 'summary' => 'Учебная карточка материала.'],
                'en' => ['title' => 'Local backups', 'summary' => 'A teaching article card.'],
            ],
            'internalNote' => 'Synthetic editorial note.',
            'owner' => ['databaseId' => 91, 'email' => '[email protected]'],
            'importBatch' => 'synthetic-batch',
        ];
    }
}

Two known keys let us check an available card and a draft. The internal array includes a local number, an editorial note, a nested owner and an import batch. Every value is artificial. The array substitutes for a data source so that we can examine the response format without an ORM or migrations.

A real Entity may have other properties, methods and relationship loading rules. This experiment neither models those behaviours nor measures database queries. The useful boundary is that an API consumer does not need to know everything the application needs for storing and editing content.

The DTO has its own JSON representation

Create src/Api/ArticleCard.php:

<?php

declare(strict_types=1);

namespace App\Api;

final readonly class ArticleCard implements \JsonSerializable
{
    public function __construct(
        public string $contentId,
        public string $locale,
        public string $title,
        public ?string $summary,
        public \DateTimeImmutable $publishedAt,
    ) {
        if ($contentId === '' || trim($title) === '') {
            throw new \InvalidArgumentException('A card needs an identity and a title.');
        }
        if (!in_array($locale, ['uk', 'ru', 'en'], true)) {
            throw new \InvalidArgumentException('Unsupported card locale.');
        }
        if ($summary !== null && trim($summary) === '') {
            throw new \InvalidArgumentException('Use null when no summary is available.');
        }
    }

    public function jsonSerialize(): array
    {
        return [
            'contentId' => $this->contentId,
            'locale' => $this->locale,
            'title' => $this->title,
            'summary' => $this->summary,
            'publishedAt' => $this->publishedAt
                ->setTimezone(new \DateTimeZone('UTC'))
                ->format('Y-m-d\TH:i:s\Z'),
        ];
    }
}

The JsonSerializable interface lets an object define its JSON representation. Here the method returns an explicit map of five fields. It does not iterate over every property in the source record or remove known secret fields from that record. A new internal field therefore needs a separate DTO change before it can appear in this response.

That differs from expecting any encoding call to know the product's policy. The json_encode documentation describes recursive encoding and the default treatment of an object's public properties; strings must use UTF-8. Our source defines its strings explicitly. This class does not implement a separate policy for cleaning arbitrary external input.

Time has one representation. DateTimeImmutable::setTimezone returns a new object with the selected timezone. We format it in UTC to the second. The original timezone does not leak into the response format, and fractional precision is deliberately outside the contract. A real system should agree that precision with its clients before changing the format.

The mapper selects data instead of copying the record

Create src/Api/ArticleCardMapper.php:

<?php

declare(strict_types=1);

namespace App\Api;

final class ArticleCardMapper
{
    public function fromRecord(array $record, string $locale): ArticleCard
    {
        $translation = $record['translations'][$locale] ?? null;
        if ($translation === null) {
            throw new \InvalidArgumentException('The requested translation is unavailable.');
        }

        return new ArticleCard(
            contentId: $record['contentId'],
            locale: $locale,
            title: $translation['title'],
            summary: $translation['summary'],
            publishedAt: $record['publishedAt'],
        );
    }
}

The mapper reads only the required values. It does not transfer the local number or nested owner, construct a public address from an incidental slug, or return every translation. A missing requested language is an error, not a reason to silently return Ukrainian text labelled as another language.

The boundary should remain narrow as the application grows. If a card needs the author's name, define a separate public field and the source of that value. Passing the entire internal owner object for one name would create a much larger contract than the client needs.

An explicit mapper makes the cost of a transformation visible. It may copy an existing value, format it or require another source. In this version, all data already exists in the array, so mapping performs no additional reads. That is a property of this fixture, not a promise that accessing any relationship on a real Entity will be free. Before applying the approach to an ORM application, examine which data is loaded and when.

An allowed field list reduces accidental response expansion, but does not establish the truth of values. If storage returns an incorrect date or translation, the mapper may accurately pass on that incorrect value. Checking the source, editorial acceptance and translation equivalence remain separate tasks. A JSON shape test should therefore not be described as validation of the entire content lifecycle.

Extend the teaching project

Create src/Controller/ArticleCardController.php:

<?php

declare(strict_types=1);

namespace App\Controller;

use App\Api\ArticleCardMapper;
use App\Catalogue\FixtureArticleCatalog;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\Routing\Attribute\Route;

final class ArticleCardController extends AbstractController
{
    #[Route(
        '/api/cards/{contentId}/{locale}',
        name: 'app_article_card',
        requirements: ['contentId' => '[a-z0-9-]+', 'locale' => '[a-z]{2}'],
        methods: ['GET'],
    )]
    public function __invoke(
        string $contentId,
        string $locale,
        FixtureArticleCatalog $catalog,
        ArticleCardMapper $mapper,
    ): JsonResponse {
        $record = $catalog->find($contentId);

        // This lab serves public fixture records only; it has no user accounts.
        if ($record === null
            || $record['publicationState'] !== 'published'
            || !in_array($locale, ['uk', 'ru', 'en'], true)
            || !isset($record['translations'][$locale])) {
            return new JsonResponse(
                ['error' => 'not_found'],
                JsonResponse::HTTP_NOT_FOUND,
                ['Cache-Control' => 'no-store'],
            );
        }

        return new JsonResponse(
            $mapper->fromRecord($record, $locale),
            JsonResponse::HTTP_OK,
            ['Cache-Control' => 'no-store'],
        );
    }
}

A Symfony controller returns a response to the request, while JsonResponse encodes JSON and sets the appropriate content type. Our route first checks whether the record exists, whether it is public and whether the language is available. Only then does it call the mapper.

The lab has no user accounts: it serves only public teaching records. A state check does not replace full user authorization. If a product has restricted content, owners or organizations, its access policy must permit reading before a card is built and returned. A DTO grants no rights to the object.

The Cache-Control: no-store header simplifies this local check; cache design is outside the example. Errors handled by the controller use the same short JSON shape. This contract does not standardize every possible framework error.

Add these registrations under the existing services key in config/services.yaml. Preserve earlier services, imports and settings; the fragment below shows additions, rather than a replacement of the whole file.

services:
    _defaults:
        autowire: true
        autoconfigure: true

    App\Catalogue\FixtureArticleCatalog: ~
    App\Api\ArticleCardMapper: ~
    App\Controller\ArticleCardController:
        tags: ['controller.service_arguments']

Test the promise made to the external client

Save tests/Unit/ArticleCardMapperTest.php:

<?php

declare(strict_types=1);

namespace App\Tests\Unit;

use App\Api\ArticleCardMapper;
use App\Catalogue\FixtureArticleCatalog;
use PHPUnit\Framework\TestCase;

final class ArticleCardMapperTest extends TestCase
{
    private function record(): array
    {
        return (new FixtureArticleCatalog())->find('article-demo-a');
    }

    private function payload(array $record, string $locale = 'en'): array
    {
        $payload = json_decode(
            json_encode((new ArticleCardMapper())->fromRecord($record, $locale), JSON_THROW_ON_ERROR),
            true,
            flags: JSON_THROW_ON_ERROR,
        );
        ksort($payload);

        return $payload;
    }

    public function testMatchesTheCompletePublicFixture(): void
    {
        $expected = json_decode(
            file_get_contents(dirname(__DIR__).'/Fixtures/article-card.en.json'),
            true,
            flags: JSON_THROW_ON_ERROR,
        );

        ksort($expected);
        self::assertSame($expected, $this->payload($this->record()));
    }

    public function testNewInternalFieldsAndRelationsDoNotChangeTheResponse(): void
    {
        $record = $this->record();
        $before = $this->payload($record);
        $record['internalNote'] = 'Changed internal note.';
        $record['owner']['email'] = '[email protected]';
        $record['newInternalField'] = ['riskScore' => 17, 'reviewerId' => 92];

        self::assertSame($before, $this->payload($record));
    }

    public function testTheLocalDatabaseIdDoesNotBecomeTheContentIdentity(): void
    {
        $record = $this->record();
        $record['databaseId'] = 9001;

        self::assertSame('article-demo-a', $this->payload($record)['contentId']);
        self::assertArrayNotHasKey('databaseId', $this->payload($record));
    }

    public function testNullSummaryIsPresentAndRemainsNull(): void
    {
        $record = $this->record();
        $record['translations']['en']['summary'] = null;
        $payload = $this->payload($record);

        self::assertArrayHasKey('summary', $payload);
        self::assertNull($payload['summary']);
    }

    public function testTheRequestedLocaleSelectsItsOwnTitle(): void
    {
        $payload = $this->payload($this->record(), 'ru');

        self::assertSame('ru', $payload['locale']);
        self::assertSame('Локальные резервные копии', $payload['title']);
    }

    public function testAMissingTranslationDoesNotSilentlyFallBack(): void
    {
        $record = $this->record();
        unset($record['translations']['en']);

        $this->expectException(\InvalidArgumentException::class);
        $this->payload($record);
    }

    public function testAnUnsupportedLocaleCannotProduceACard(): void
    {
        $record = $this->record();
        $record['translations']['pl'] = $record['translations']['en'];

        $this->expectException(\InvalidArgumentException::class);
        $this->payload($record, 'pl');
    }

    public function testBlankSummaryMustBeRepresentedExplicitlyAsNull(): void
    {
        $record = $this->record();
        $record['translations']['en']['summary'] = '   ';

        $this->expectException(\InvalidArgumentException::class);
        $this->payload($record);
    }
}

Eight test methods check the complete fixture, new internal fields, independence from a local number, explicit null, the correct language and rejection of silent fallback. Running them requires only the shown file and fixture; the reader needs no other private tests. The Symfony Testing documentation explains PHPUnit integration and the different kinds of checks.

composer validate --strict --no-check-publish
composer check-platform-reqs
php bin/console lint:yaml config/services.yaml
php bin/console lint:container --env=dev
php bin/console debug:router app_article_card
APP_ENV=test php bin/phpunit tests/Unit/ArticleCardMapperTest.php --testdox

The complete fixture comparison is deliberately strict. It protects the selected contract revision, rather than proving compatibility with every future extension. JSON object key order is not part of our contract. Before comparison, the test sorts the top-level keys and then compares types and values strictly.

Run the local server in a separate terminal:

APP_ENV=dev php -S 127.0.0.1:8000 -t public public/index.php

Check the routes from another terminal:

curl -i http://127.0.0.1:8000/api/cards/article-demo-a/en
curl -i http://127.0.0.1:8000/api/cards/article-demo-draft/en
curl -i http://127.0.0.1:8000/api/cards/unknown/en
curl -i http://127.0.0.1:8000/api/cards/article-demo-a/pl

The expected statuses, in order, are 200, 404, 404 and 404. The first response should contain exactly the card fields; the others should reject the request without returning the internal record. Stop the server after checking. These HTTP requests complement mapper tests because they exercise the route, container and actual response encoding.

If the fixture test succeeds but the HTTP request returns no card, investigate another boundary: route registration, service availability, record selection or its state check. If HTTP returns a successful response with an extra field, verify that the controller actually uses the DTO rather than another serialization path. A small unit test and a real request are useful together because they answer different questions.

A negative scenario also has a meaningful result. A draft must not become an empty successful card, and an unknown language must not produce success with an arbitrary translation. Using the same rejection for an absent record and a nonpublic one is a choice made for this route. It does not prove the complete absence of every side signal in a larger application; this example checks a particular status and response body.

Evolving the contract

A new storage field and a new API field are different changes. The first may leave the card untouched. The second requires a decision about meaning, type, absent data and client expectations. Even adding a field should be considered in the context of consumers: a strict client may validate a closed schema.

Changing the external contract requires coordinated updates to the DTO, the mapper where necessary, the schema, the fixture and the explanation. The access rule is checked separately. With those parts explicit, an internal record change no longer automatically becomes a public change, and the card has a clear boundary and verifiable content.

  1. Symfony Core Entity or DTO: which data should a page receive from storage?
  2. Architecture Admin, Frontend, and API: three distinct responsibilities
  3. API API languages and links: one article across three routes
  4. API Testing an API without a live database: what a fixture proves and what it does not

A project by the author · Weather Solution200

After reading, a look outside.

Temperature, rain and wind in your city. Check the forecast and plan the hours ahead.

Check the forecast
Next article