Documentation: tomaj.github.io/nette-api (English, slovensky)
Robust REST APIs inside your Nette application. Nette API adds a complete API layer to Nette, wired through Nette DI with one handler class per endpoint. You register endpoints and write handlers with your business logic; the library takes care of routing, typed and validated params, authorization, rate limits, output checks, error responses, logging, OpenAPI and a web console for trying the API.
Nette API 3.x needs PHP 8.3 or newer. 4.0, in development on master, needs PHP 8.4 or newer, see UPGRADE-4.0.md.
composer require tomaj/nette-apiRoute /api to the library presenter:
$router->addRoute('/api/v<version>/<package>[/<apiAction>][/<params>]', 'Api:Api:default');Register the services and your endpoints in NEON:
application:
mapping:
Api: Tomaj\NetteApi\Presenters\*Presenter
services:
- Tomaj\NetteApi\Presenters\ApiPresenter
apiOutputConfigurator: Tomaj\NetteApi\Output\Configurator\DebuggerConfigurator
apiErrorHandler: Tomaj\NetteApi\Error\DefaultErrorHandler
- App\Api\HelloHandler
apiDecider:
factory: Tomaj\NetteApi\ApiDecider
setup:
- addApi(Tomaj\NetteApi\EndpointIdentifier('GET', 1, 'hello'), App\Api\HelloHandler, Tomaj\NetteApi\Authorization\NoAuthorization())For new projects we recommend RFC 9457 Problem Details errors: register Tomaj\NetteApi\Error\ProblemDetailsErrorHandler as apiErrorHandler. DefaultErrorHandler stays the default, so existing clients that read message keep working.
Write the handler:
final class HelloHandler extends BaseHandler
{
public function params(): array
{
return [
(new GetInputParam('name'))->setDefault('world'),
];
}
public function handle(array $params): ResponseInterface
{
return new JsonApiResponse(200, ['message' => 'Hello ' . $params['name'] . '!']);
}
}curl http://localhost:8000/api/v1/hello?name=Nette
# {"message":"Hello Nette!"}The getting started guide explains every line.
Since 4.0 you can use the DI extension instead of the services: above:
extensions:
api: Tomaj\NetteApi\DI\NetteApiExtension
api:
endpoints:
- {method: GET, version: 1, package: hello, handler: App\Api\HelloHandler}Or put #[Get(1, 'hello')] on the handler class and let the extension find it with api: discovery: paths: [%appDir%/Api], see attribute endpoints.
| Topic | Page |
|---|---|
| How a request is processed | Architecture |
| What each layer does: ApiDecider, presenter, authorization, params, handler, outputs | Layers, ApiDecider, ApiPresenter pipeline |
| Handlers, params and outputs | Handlers, Params, Outputs |
| Bearer tokens, API keys, HTTP Basic, IP restrictions | Authorization |
| Rate limits, CORS, logging, errors | Rate limiting, CORS, Logging, Error handling |
OpenAPI, web console, {apiLink} |
OpenAPI, Web console, Links and versions |
One api: neon section instead of services (4.0) |
DI extension |
#[Get(1, 'users')] on the handler class (4.0) |
Attribute endpoints |
| Every class | Reference |
- CORS:
setCorsHeader('auto')reflects any site from theRefererheader and allows credentials. UsesetCorsAllowedOrigins([...])(since 3.6.0) or one fixed origin. 4.0 renames it to'reflect-unsafe'('auto'throws) and sends no CORS headers until you configure them, and addssetCorsOriginValidator()for origins not known in advance. See CORS. - Logs: in 3.x request headers reach
ApiLoggerInterfaceas they arrived, unless you callsetMaskedLogHeaders()onApiPresenter(since 3.6.0). 4.0 masksAuthorization,Cookie,X-Api-Key, headers likeX-Auth-Token, query parameters likeapi_keyand the names of your API key authorizations by default, as***, a partial value, a hash or nothing. See Logging. - Tokens and passwords:
BasicAuthenticationandStaticTokenRepositorycompare withhash_equals()(since 3.6.0). See Authorization.
Sixteen runnable projects in examples/, each with an e2e.sh test that CI runs against the current code:
hello world, params and validation, authorization and rate limit, CORS, OpenAPI and console, logging and errors, Problem Details, DI extension, attribute endpoints, custom authorization, JSON and raw body, file upload, pagination, API versions, rate limit, testing.
See UPGRADE.md and CHANGELOG.md. Documentation for 2.x is the README of 2.13.0.
composer install
vendor/bin/phpunitCoverage is opt-in: composer coverage (needs Xdebug).
Please see CONTRIBUTING. The documentation lives in docs/.
If you discover any security related issues, please email [email protected] instead of using the issue tracker.
The MIT License (MIT). Please see License File for more information.