Skip to content
tomajPublic

About

API solution for Nette framework with interactive generated console for each api

Resources

Contributing

Stars

36 stars

Watchers

4 watching

Forks

Repository files navigation

Nette API

Documentation: tomaj.github.io/nette-api (English, slovensky)

PHPunit Examples OpenSSF Scorecard Latest Stable Version

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.

A request goes through ApiDecider, the rate limit, authorization and param error reporting to the handler; the output is checked and logged, and the response goes back to the client; 429, 401 and 400 errors go back to the client too, and an unknown URL becomes a 404 from DefaultHandler, which is logged

Installation

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-api

Quick start

Route /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())

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.

What is in the documentation

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
Every class Reference

Security notes

  • CORS: setCorsHeader('auto') reflects any site from the Referer header and allows credentials. Use setCorsAllowedOrigins([...]) (since 3.6.0) or one fixed origin. See CORS.
  • Logs: request headers reach ApiLoggerInterface as they arrived. Call setMaskedLogHeaders() on ApiPresenter (since 3.6.0) to log *** instead of Authorization, Cookie, X-Api-Key and other secrets. See Logging.
  • Tokens and passwords: BasicAuthentication and StaticTokenRepository compare with hash_equals() (since 3.6.0). See Authorization.

Examples

Thirteen 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, custom authorization, JSON and raw body, file upload, pagination, API versions, rate limit, testing.

Upgrading

See UPGRADE.md and CHANGELOG.md. Documentation for 2.x is the README of 2.13.0.

Testing

composer install
vendor/bin/phpunit

Coverage is opt-in: composer coverage (needs Xdebug).

Contributing

Please see CONTRIBUTING. The documentation lives in docs/.

Security

If you discover any security related issues, please email tomasmajer@gmail.com instead of using the issue tracker.

License

The MIT License (MIT). Please see License File for more information.

About

API solution for Nette framework with interactive generated console for each api

Resources

Contributing

Stars

36 stars

Watchers

4 watching

Forks

Releases

Packages

Used by

Contributors

Languages