All Projects → sunrise-php → Http Router

sunrise-php / Http Router

Licence: mit
🎉 Release 2.0 is released! Very fast HTTP router for PHP 7.1+ (incl. PHP8 with attributes) based on PSR-7 and PSR-15 with support for annotations and OpenApi (Swagger)

Projects that are alternatives of or similar to Http Router

Fastapi
FastAPI framework, high performance, easy to learn, fast to code, ready for production
Stars: ✭ 39,588 (+31825.81%)
Mutual labels:  swagger, openapi, openapi3
Openapi Spring Webflux Validator
🌱 A friendly kotlin library to validate API endpoints using an OpenApi 3.0 and Swagger 2.0 specification
Stars: ✭ 67 (-45.97%)
Mutual labels:  swagger, openapi, openapi3
Rolodex
📇API Documentation Generator for Phoenix
Stars: ✭ 34 (-72.58%)
Mutual labels:  swagger, openapi, openapi3
Swagger Core
Examples and server integrations for generating the Swagger API Specification, which enables easy access to your REST API
Stars: ✭ 6,898 (+5462.9%)
Mutual labels:  swagger, openapi, openapi3
Swurg
Parse OpenAPI documents into Burp Suite for automating OpenAPI-based APIs security assessments (approved by PortSwigger for inclusion in their official BApp Store).
Stars: ✭ 94 (-24.19%)
Mutual labels:  swagger, openapi, openapi3
Widdershins
OpenAPI / Swagger, AsyncAPI & Semoasa definitions to (re)Slate compatible markdown
Stars: ✭ 856 (+590.32%)
Mutual labels:  swagger, openapi, openapi3
Vue Openapi
OpenAPI viewer component for VueJS
Stars: ✭ 66 (-46.77%)
Mutual labels:  swagger, openapi, openapi3
Schemathesis
A modern API testing tool for web applications built with Open API and GraphQL specifications.
Stars: ✭ 768 (+519.35%)
Mutual labels:  swagger, openapi, openapi3
Go Tgbot
Golang telegram bot API wrapper, session-based router and middleware
Stars: ✭ 90 (-27.42%)
Mutual labels:  swagger, middleware, router
Openapi Viewer
Browse and test a REST API described with the OpenAPI 3.0 Specification
Stars: ✭ 82 (-33.87%)
Mutual labels:  swagger, openapi, openapi3
Openapi Gui
GUI / visual editor for creating and editing OpenAPI / Swagger definitions
Stars: ✭ 891 (+618.55%)
Mutual labels:  swagger, openapi, openapi3
Router
🍭灵活的组件化路由框架.
Stars: ✭ 1,502 (+1111.29%)
Mutual labels:  annotations, annotation, router
Apispec
A pluggable API specification generator. Currently supports the OpenAPI Specification (f.k.a. the Swagger specification)..
Stars: ✭ 831 (+570.16%)
Mutual labels:  swagger, openapi, openapi3
Spectral
A flexible JSON/YAML linter for creating automated style guides, with baked in support for OpenAPI v2 & v3.
Stars: ✭ 876 (+606.45%)
Mutual labels:  swagger, openapi, openapi3
Oapi Codegen
Generate Go client and server boilerplate from OpenAPI 3 specifications
Stars: ✭ 806 (+550%)
Mutual labels:  swagger, openapi, openapi3
Springdoc Openapi
Library for OpenAPI 3 with spring-boot
Stars: ✭ 1,113 (+797.58%)
Mutual labels:  swagger, openapi, openapi3
Full Stack Fastapi Postgresql
Full stack, modern web application generator. Using FastAPI, PostgreSQL as database, Docker, automatic HTTPS and more.
Stars: ✭ 7,635 (+6057.26%)
Mutual labels:  swagger, openapi, openapi3
Kin Openapi
OpenAPI 3.0 implementation for Go (parsing, converting, validation, and more)
Stars: ✭ 776 (+525.81%)
Mutual labels:  swagger, openapi, openapi3
Express Jsdoc Swagger
Swagger OpenAPI 3.x generator
Stars: ✭ 69 (-44.35%)
Mutual labels:  swagger, openapi, openapi3
Kaizen Openapi Editor
Eclipse Editor for the Swagger-OpenAPI Description Language
Stars: ✭ 97 (-21.77%)
Mutual labels:  swagger, openapi, openapi3

HTTP router for PHP 7.1+ (incl. PHP 8 with attributes) based on PSR-7 and PSR-15 with support for annotations and OpenApi (Swagger)

Build Status Code Coverage Scrutinizer Code Quality Total Downloads Latest Stable Version License


Installation

composer require 'sunrise/http-router:^2.6'

QuickStart

The example uses other sunrise packages, but you can use, for example, zend/diactoros or any other.

composer require sunrise/http-message sunrise/http-server-request
use Sunrise\Http\Message\ResponseFactory;
use Sunrise\Http\Router\RequestHandler\CallableRequestHandler;
use Sunrise\Http\Router\RouteCollector;
use Sunrise\Http\Router\Router;
use Sunrise\Http\ServerRequest\ServerRequestFactory;

use function Sunrise\Http\Router\emit;

$collector = new RouteCollector();

$collector->get('home', '/', new CallableRequestHandler(function ($request) {
    return (new ResponseFactory)->createJsonResponse(200, [
        'status' => 'ok',
    ]);
}));

$router = new Router();
$router->addRoute(...$collector->getCollection()->all());

$request = ServerRequestFactory::fromGlobals();
$response = $router->handle($request);

emit($response);

Examples of using

Study sunrise/awesome-skeleton to understand how this can be used.

Strategy loading routes from configs

use Sunrise\Http\Router\Loader\CollectableFileLoader;
use Sunrise\Http\Router\Router;

$loader = new CollectableFileLoader();
$loader->attach('routes/api.php');
$loader->attach('routes/admin.php');
$loader->attach('routes/public.php');

// or attach a directory...
// [!] available from version 2.2
$loader->attach('routes');

// or attach an array...
// [!] available from version 2.4
$loader->attachArray([
    'routes/api.php',
    'routes/admin.php',
    'routes/public.php',
]);

$router = new Router();
$router->load($loader);

// if the router is used as a request handler
$response = $router->handle($request);

// if the router is used as middleware
$response = $router->process($request, $handler);

Strategy loading routes from descriptors (annotations or attributes)

use Doctrine\Common\Annotations\AnnotationRegistry;
use Sunrise\Http\Router\Loader\DescriptorDirectoryLoader;
use Sunrise\Http\Router\Router;

// necessary if you will use annotations (annotations isn't attributes)...
AnnotationRegistry::registerLoader('class_exists');

$loader = new DescriptorDirectoryLoader();
$loader->attach('src/Controller');

// or attach an array
// [!] available from version 2.4
$loader->attachArray([
    'src/Controller',
    'src/Bundle/BundleName/Controller',
]);

$router = new Router();
$router->load($loader);

// if the router is used as a request handler
$response = $router->handle($request);

// if the router is used as middleware
$response = $router->process($request, $handler);

Without loading strategy

use App\Controller\HomeController;
use Sunrise\Http\Router\RouteCollector;
use Sunrise\Http\Router\Router;

$collector = new RouteCollector();
$collector->get('home', '/', new HomeController());

$router = new Router();
$router->addRoute(...$collector->getCollection()->all());

// if the router is used as a request handler
$response = $router->handle($request);

// if the router is used as middleware
$response = $router->process($request, $handler);

Route Annotation Example

Minimal annotation view
/**
 * @Route(
 *   name="api_v1_entry_update",
 *   path="/api/v1/entry/{id<@uuid>}(/{optionalAttribute})",
 *   methods={"PATCH"},
 * )
 */
final class EntryUpdateRequestHandler implements RequestHandlerInterface
Full annotation
/**
 * @Route(
 *   name="api_v1_entry_update",
 *   host="api.host",
 *   path="/api/v1/entry/{id<@uuid>}(/{optionalAttribute})",
 *   methods={"PATCH"},
 *   middlewares={
 *     "App\Middleware\CorsMiddleware",
 *     "App\Middleware\ApiAuthMiddleware",
 *   },
 *   attributes={
 *     "optionalAttribute": "defaultValue",
 *   },
 *   summary="Updates an entry by UUID",
 *   description="Here you can describe the method in more detail...",
 *   tags={"api", "entry"},
 *   priority=0,
 * )
 */
final class EntryUpdateRequestHandler implements RequestHandlerInterface

Route Attribute Example

Minimal attribute view
use Sunrise\Http\Router\Attribute\Route;

#[Route(
    name: 'api_v1_entry_update',
    path: '/api/v1/entry/{id<@uuid>}(/{optionalAttribute})',
    methods: ['PATCH'],
)]
final class EntryUpdateRequestHandler implements RequestHandlerInterface
Full attribute
use Sunrise\Http\Router\Attribute\Route;

#[Route(
    name: 'api_v1_entry_update',
    host: 'api.host',
    path: '/api/v1/entry/{id<@uuid>}(/{optionalAttribute})',
    methods: ['PATCH'],
    middlewares: [
        \App\Middleware\CorsMiddleware::class,
        \App\Middleware\ApiAuthMiddleware::class,
    ],
    attributes: [
        'optionalAttribute' => 'defaultValue',
    ],
    summary: 'Updates an entry by UUID',
    description: 'Here you can describe the method in more detail...',
    tags: ['api', 'entry'],
    priority: 0,
)]
final class EntryUpdateRequestHandler implements RequestHandlerInterface

Useful to know

OpenApi (Swagger)

composer require 'sunrise/http-router-openapi:^1.1'

Generation documentation for Swagger (OAS)

use Sunrise\Http\Router\OpenApi\Object\Info;
use Sunrise\Http\Router\OpenApi\OpenApi;

$openApi = new OpenApi(new Info('0.0.1', 'API'));

$openApi->addRoute(...$router->getRoutes());

$openApi->toArray();

Validation a request body via Swagger documentation

use Sunrise\Http\Router\OpenApi\Middleware\RequestBodyValidationMiddleware;

$route->addMiddleware(new RequestBodyValidationMiddleware());

or using annotations:

/**
 * @Route(
 *   name="foo",
 *   path="/foo",
 *   methods={"post"},
 *   middlewares={
 *     "Sunrise\Http\Router\OpenApi\Middleware\RequestBodyValidationMiddleware",
 *   },
 * )
 */

Generation a route URI

$uri = $router->generateUri('route.name', [
    'attribute' => 'value',
], true);

Run a route

$response = $router->getRoute('route.name')->handle($request);

Route grouping

$collector->group(function ($collector) {
    $collector->group(function ($collector) {
        $collector->group(function ($collector) {
            $collector->get('api.entry.read', '/{id<\d+>}', ...)
                ->addMiddleware(...); // add the middleware(s) to the route...
        })
        ->addPrefix('/entry') // add the prefix to the group...
        ->unshiftMiddleware(...); // add the middleware(s) to the group...
    })
    ->addPrefix('/v1') // add the prefix to the group...
    ->unshiftMiddleware(...); // add the middleware(s) to the group...
})
->addPrefix('/api') // add the prefix to the group...
->unshiftMiddleware(...); // add the middleware(s) to the group...

Route patterns

$collector->get('api.entry.read', '/api/v1/entry/{id<\d+>}(/{optional<\w+>})');

Hosts (available from version 2.6.0)

Note: if you don't assign a host for a route, it will be available on any hosts!

// move the hosts table into the settings...
$router->addHost('public.host', 'www.example.com');
$router->addHost('admin.host', 'secret.example.com');
$router->addHost('api.host', 'api.example.com');

// the route will available only on the `secret.example.com` host...
$route->setHost('admin.host');

// routes in the group will available on the `secret.example.com` host...
$collector->group(function ($collector) {
    // some code...
})
->setHost('admin.host');

Test run

composer test

Useful links

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].