TYPO3 REST API foundation. Built using an own middleware stack

2.0.0 2022-07-04 09:50 UTC

This package is auto-updated.

Last update: 2023-06-04 11:58:35 UTC


README

pipeline status

Powered by co-stack.com

About

This TYPO3 Extension adds a generic API capability to TYPO3. The strength of this extension lies in its integration in TYPO3 itself and its ease of being used by other extensions. If you want to create a fast and safe API in TYPO3 you should use this extension.

There is no purpose in installing this extension without another extension that requires it.

Usage

Creating an API endpoint with EXT:api is simple and fast. EXT:api and your extension must be installed for the following steps.

  1. Create your API endpoint class. It can be anywhere but it is good practice to put it in Classes/Api. Name your class after its use case. (e.g. Vendor\Packaga\Api\VersionApi). Your API class must implement the interface \CoStack\Api\Api\Api. Return an array with some values to begin with.
  2. Create your API registration file in Configuration/Api.php and register your API class. The file must return an associative array. The associative index is the ROUTE, or API endpoint name and will be part of the URL. Here is an example with the StatusApi class.
     return [
        'status' => [
            'class' => \CoStack\Api\Api\StatusApi::class,
        ],
     ];
    
  3. Login as administrator to your TYPO3 Backend. Go to the root page (ID 0) and select the list module. Create a new API token. Your registered API class should show up in the API scope list. Give your token a name and add your API endpoint to the list of APIs in scope. Safe the token to generate the token's secret.
  4. You can test your API by using curl. Replace SECRET, DOMAIN, EXTKEY and ROUTE with your values:\ curl -H "Accept: application/json" -H "X-T3API-TOKEN: <SECRET>" https://<DOMAIN>/api/<EXTKEY>/<ROUTE>\ Example: curl -H "Accept: application/json" -H "X-T3API-TOKEN: a220d5a473232e636f845e0f6919981a1baf13e97758d83b2bde7c5ec68954b7" https://local.myproject.de/api/api/status You should see the array JSON encoded.

Advanced usage

Response formatting

Content Type determination

Responses are always formatted based on certain criteria. Currently, there are 3 criterias which can determine the response content type. They are evaluated in the following order:

  1. URL file extension: Calling an API url with .json or .xml at the end will force the response to be in that format.
  2. Accept header: Accept headers can contain multiple mime types. They will be ordered by priority and the first mime type which is supported will be used (see Formatter).
  3. Route defaults: Routes can define a default mime type that will be used when there is no file extension or accept header. Multiple mime types are tried in order until the first supported is found (see Formatter).

Formatter

Formatter are classes that can convert a PHP array into another mime type. The most used Formatter is \CoStack\Api\Core\Response\Formatter\JsonFormatter.

Register your own formatter by simply implementing the \CoStack\Api\Core\Response\Formatter\ResponseFormatter interface or rather extend \CoStack\Api\Core\Response\Formatter\AbstractFormatter:

<?php

namespace Vendor\Ext\Api\Response\Formatter;

class SerializationFormatter extends \CoStack\Api\ResponseFormatter\AbstractFormatter
{
    protected $supportedMimes = [
        'application/php-serialized',
    ];

    public function process(array $data): string
    {
        return serialize($data);
    }
}

Additional middleware

The EXT:api middleware stack is fully configurable. Register your own middleware in Configuration/RequestMiddlewares.php:

<?php

return [
    'api' => [
        'vendor/ext/request/logger' => [
            'target' => \Vendor\Ext\Middleware\Api\Logger::class,
            'before' => [
                'co-stack/api/router',
            ],
        ],
    ],
];

API route configuration

Each API endpoint has a set of configuration options. This example shows the full set of configuration options:

<?php
declare(strict_types=1);
return [
    '_default' => [
        'v1' => [
            'mimes' => [
                'application/json',
            ],
        ],
        'public' => [
            'public' => true,
        ],
    ],
    'v1/extension/version' => [
        'class' => \CoStack\Api\Api\ExtensionVersionApi::class,
    ],
    'v1/file/info' => [
        'class' => \CoStack\Api\Api\FileInfoApi::class,
    ],
    'v1/status' => [
        'class' => \CoStack\Api\Api\StatusApi::class,
        'public' => true,
    ],
    'v1/discovery' => [
        'class' => \CoStack\Api\Api\DiscoveryApi::class,
        'mimes' => [
            'application/xml',
        ],
    ],
    'public/discovery' => [
        'class' => \CoStack\Api\Api\PublicDiscoveryApi::class,
        'mimes' => [
            'application/xml',
            'application/json',
        ],
    ],
];

Explanation:

  • class: The FQCN of your class that implements the API.
  • public: Routes which are public don't require the X-T3API-TOKEN header. They are always available.
  • mimes: Define default mime types for the response formatting.
  • _default: The _default key is reserved to define defaults for all routes matching the sub-keys. In this example _default contains v1 and v2. All routes beginning with v1 will inhert the mimes setting. The v2 defaults contains 'public' => true which will make all routes starting with public publicly available.

Debugging

To develop and debug your API calls you should set TYPO3's displayErrors to wither 1 for local development. In public or production environments displayErrors should be -1 and your devIPmask should be set. Enabling this setting will show exception instead of failing silently.

curl

Your API responses may be empty if something went wrong. You can add following options to your curl call to get more information:

  • -I: Display the response headers (especially usefull if you do not see any response).
  • -H "X-T3API-SAPI: cli": Force the exception to be rendered for CLI.

Following HTTP Status codes are currently implemented:

  • 403: You did not include an authentication header (X-T3API-TOKEN) or the provided secret is incorrect.
  • 406: You did not include an accept header in your request or the accepted mime is not supported. Always try with application/json first.
  • 429: You hit the hard rate limit. Increase the requests per minute in the extension settings. You can set this to 0 to disable the rate limiter, but you must be aware of security implications (e.g. DoS).
  • 500: An exception occurred in your API class. Check the logs.

PhpStorm

When you do not get the results you expect from an API call you can debug requests with xDebug and PhpStorm.

Please use the internet search if you have any questions about xDebug or PhpStorm. We will not answer inquiries on these topics.

  1. Create a new .http scratch file. Replace SECRET, DOMAIN, EXTKEY and ROUTE with your values):
     https://<DOMAIN>/api/<EXTKEY>/<ROUTE>
     Accept: application/json
     X-T3API-TOKEN: <SECRET>
    
  2. Add a stop point in \CoStack\Api\Middleware\ApiMiddleware::process.
  3. Click on the green arrow left of the URL and select PHP Debug.
  4. If your project is set up correctly it should hit your stop point.