baraja-core / structured-api
Complex library for definition of your structured API endpoint as class with schema.
Installs: 173 065
Dependents: 12
Suggesters: 0
Security: 0
Stars: 7
Watchers: 2
Forks: 0
Open Issues: 11
Requires
- php: ^8.1
- ext-iconv: *
- ext-json: *
- ext-mbstring: *
- baraja-core/serializer: ^1.0
- baraja-core/service-method-invoker: ^2.2.1
- baraja-core/url: ^1.1
- nette/application: ^3.1
- nette/caching: ^3.1
- nette/di: ^3.0
- nette/http: ^3.1
- nette/robot-loader: ^3.3
Requires (Dev)
- baraja-core/cas: ^1.0
- baraja-core/localization: ^2.0
- phpstan/extension-installer: ^1.1
- phpstan/phpstan: ^1.0
- phpstan/phpstan-deprecation-rules: ^1.0
- phpstan/phpstan-nette: ^1.0
- phpstan/phpstan-strict-rules: ^1.0
- roave/security-advisories: dev-master
- spaze/phpstan-disallowed-calls: ^2.0
- tracy/tracy: ^2.8
- dev-master
- v4.1.1
- v4.1.0
- v4.0.3
- v4.0.2
- v4.0.1
- v4.0.0
- v3.5.1
- v3.5.0
- v3.4.0
- v3.3.3
- v3.3.2
- v3.3.1
- v3.3.0
- v3.2.1
- v3.2.0
- v3.1.2
- v3.1.1
- v3.1.0
- v3.0.6
- v3.0.5
- v3.0.4
- v3.0.3
- v3.0.2
- v3.0.1
- v3.0.0
- v2.5.0
- v2.4.6
- v2.4.5
- v2.4.4
- v2.4.3
- v2.4.2
- v2.4.1
- 2.4.0
- v2.3.2
- v2.3.1
- v2.3.0
- v2.2.1
- v2.2.0
- v2.1.3
- v2.1.2
- v2.1.1
- v2.1.0
- v2.0.10
- v2.0.9
- v2.0.8
- v2.0.7
- v2.0.6
- v2.0.5
- v2.0.4
- v2.0.3
- V2.0.2
- v2.0.1
- v2.0.0
- v1.2.0
- v1.1.2
- v1.1.1
- v1.1.0
- v1.0.12
- v1.0.11
- v1.0.10
- v1.0.9
- v1.0.8
- v1.0.7
- v1.0.6
- v1.0.5
- v1.0.4
- v1.0.3
- v1.0.2
- v1.0.1
- dev-imgbot
- dev-renovate/configure
- dev-restyled/renovate/configure
- dev-dependabot/add-v2-config-file
This package is auto-updated.
Last update: 2024-11-09 21:22:26 UTC
README
BRJ organisation
Structured REST API in PHP
Full compatible smart structured API defined by schema.
- Define full type-hint input parameters,
- Validate returned data by schema,
- Full compatible with Nette framework,
- Inject dependencies by
#[Inject]
attribute (or old@inject
annotation syntax) in public property.
๐ฆ Installation & Basic Usage
This package can be installed using PackageRegistrator which is also part of the Baraja Sandbox. If you are not using it, you have to install the package manually following this guide.
A model configuration can be found in the common.neon
file inside the root of the package.
To manually install the package call Composer and execute the following command:
$ composer require baraja-core/structured-api
๐ ๏ธ API endpoint
API endpoint is simple class with action methods and dependencies. For best comfort please use your custom BaseEndpoint with declaring all required dependencies.
Simple example:
<?php declare(strict_types=1); namespace App\Model; final class MyAwesomeEndpoint extends BaseEndpoint { /** * This is test API endpoint as demonstration of inner logic. * * @param string $hello some user-defined parameter. */ public function actionDefault(string $hello = 'world'): MyAwesomeResponse { // The endpoint response can be simply returned as an simple array or typed object. // A type object is much better because it will be used as the basis for documentation. // It will be automatically converted to JSON. return new MyAwesomeResponse( name: 'Test API endpoint', hello: $hello, ); } // or use old syntax: /** * This is test API endpoint as demonstration of inner logic. * * @param string $hello some user-defined parameter. */ public function actionDefault(string $hello = 'world'): void { $this->sendJson([ 'name' => 'Test API endpoint', 'hello' => $hello, ]); } // or return simple array directly: /** * @param array<mixed, mixed> $data */ public function postCreateUser(array $data): array { return [ 'state' => 'ok', 'data' => $data, ]; } }
Method actionDefault
is used for request in format /api/v1/test
with query parameter ?hello=...
.
Method postCreateUser
will be called by POST request with all data.
Always return the response from the endpoint directly as the return type of the method. This makes static analysis easier for other tools (for example, for checking code integrity or generating documentation). The sendJson()
, sendOk()
, and sendError()
methods are still supported, but may be marked as deprecated in the future.
๐ Endpoint registration
If you use the Nette Framework, all endpoints will be registered automatically. This provides an extension for DIC.
To register automatically, simply inherit BaseEndpoint
or implement the Baraja\StructuredApi\Endpoint
interface.
๐ HTTP methods
The library supports all HTTP methods for the REST API. The selection of the HTTP method is solved by the method name.
You can specify the HTTP method at the beginning of the method name, or use an alias:
final class MyAwesomeEndpoint extends BaseEndpoint { public function getDefault(): void { // this logic will be called as GET. } public function actionDefault(): void { // this logic will be called as GET too, // because `action` prefix is alias for GET. } public function postDetail(string $id, string $name, ?string $description = null): void { // this logic will be called as POST. } }
List of aliases (aliases are optional):
action
asGET
update
asPUT
create
asPOST
๐พ Obtaining raw data
For processing complex data structures, it may be useful to obtain the data in its original raw form.
The library reserves the key variable array $data
, which always contains the original input values from the user, regardless of validation.
For example:
final class OrderEndpoint extends BaseEndpoint { public function postProcessOrder(array $data): void { // variable $data contains all raw data from user. } }
โ Validation
In the runtime, when calling methods, the passed arguments against the method definition and data types are validated. This ensures that the endpoint is never called with incorrect data.
The library guarantees that you will always get the data in the type you request. If you need to define the type more complicated, you can use a comment annotation.
Combined example:
final class ArticleEndpoint extends BaseEndpoint { /** * @param string|null $locale in format "cs" or "en" * @param int $page real page number for filtering, 1 => first page ... "n" page * @param int $limit in interval <0, 500) * @param string|null $status matching constant self::STATUS_* (null, all, published, trash) * @param string|null $query smart search query * @param string|null $filterFrom find all articles from this date * @param string|null $filterTo find all articles to this date * @param string|null $sort sort by supported field * @param string|null $orderBy direction by `ASC` or `DESC` */ public function actionDefault( ?string $locale = null, int $page = 1, int $limit = 32, ?string $status = null, ?string $query = null, ?string $filterFrom = null, ?string $filterTo = null, ?string $sort = null, ?string $orderBy = null, ): void { } }
The library takes full advantage of PHP 7 and always checks data types. If the data is passed in the wrong type (for example, a boolean cannot be passed by the GET method), it performs an automatic conversion or throws an error.
If the argument contains a default value, it is automatically marked as optional. If the user does not pass a value, the default is used. All mandatory arguments must always be passed, if not, your logic will not be called at all.
๐ Smart response
The library contains a number of built-in methods for elegant handling of all important return states.
For example, if we want to get the detail of an article by ID and return its detail from the database, the use is completely intuitive:
final class ArticleEndpoint extends BaseEndpoint { public function actionDetail(string $id): void { // your logic for fetch data from database // your response $this->sendJson([ 'id' => $id, 'title' => 'My awesome article', 'content' => '...', ]); } }
Each method can return output either via send
methods or directly as a type object. A more modern approach is to return the entire object, as this gives us type checking and the underlying basis for automatically generated documentation.
Warning: If you do not pass any output (by method or return statement), endpoint processing will fail.
When processing actions, it is a good idea to return success or error information:
final class ArticleEndpoint extends BaseEndpoint { public function createDetail(string $title, string $content, ?string $perex = null): void { try { // creating in database... $this->sendOk([ 'id' => 123, ]); } catch (\Exception $e) { $this->sendError('Can not create article because ...'); } } }
๐ Permissions
๐ฉWarning: If you do not set the rights at all, by default all endpoints are private and you must log in to call them! ๐ฎ
All API requests are validated at runtime. If you want to allow all users access to your endpoints, please add the #[PublicEndpoint]
attribute to class.
For example (this endpoint will be public):
#[PublicEndpoint] final class ProductEndpoint extends BaseEndpoint { }
To restrict rights, define an #[Role]
attribute over a class or method.
For example (only administrators and moderators can call this endpoint):
#[Role(roles: ['admin', 'moderator'])] final class ArticleEndpoint extends BaseEndpoint { }
Rights settings can also be combined. For example, in a public endpoint, restrict rights to a specific method only:
#[PublicEndpoint] final class SitemapEndpoint extends BaseEndpoint { #[Role(roles: 'admin')] public function actionClearCache(): void { // your secured implementation } }
๐ Check API token
If you want to provide the API to your external partners or to provide secure communication with another application, it is a good idea to use authentication of all requests via an API token. There is an official extension structured-api-token-authorizer for this use.
๐บ๏ธ Project endpoint documentation
When developing a real application, you will often need to pass work between the backend and the frontend.
To describe all endpoints, the package offers an optional extension that generates documentation automatically based on real code scanning.
Try the Structured API Documentation.
๐ License
baraja-core/structured-api
is licensed under the MIT license. See the LICENSE file for more details.