{"id":50994943,"url":"https://github.com/nextphp-projects/rest","last_synced_at":"2026-06-20T08:02:00.142Z","repository":{"id":246539013,"uuid":"821424721","full_name":"nextphp-projects/rest","owner":"nextphp-projects","description":"Provides tools for building and managing RESTful APIs, enabling easy creation, reading, updating, and deletion of resources over HTTP.","archived":false,"fork":false,"pushed_at":"2024-07-04T08:39:56.000Z","size":25,"stargazers_count":0,"open_issues_count":0,"forks_count":0,"subscribers_count":1,"default_branch":"main","last_synced_at":"2025-10-14T05:08:41.380Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":null,"language":"PHP","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/nextphp-projects.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2024-06-28T14:04:23.000Z","updated_at":"2024-07-04T08:38:57.000Z","dependencies_parsed_at":"2024-06-28T15:28:38.926Z","dependency_job_id":"4eba705e-e74a-42d7-97c1-550291bc45a9","html_url":"https://github.com/nextphp-projects/rest","commit_stats":null,"previous_names":["nextphp-projects/rest"],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/nextphp-projects/rest","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/nextphp-projects%2Frest","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/nextphp-projects%2Frest/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/nextphp-projects%2Frest/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/nextphp-projects%2Frest/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/nextphp-projects","download_url":"https://codeload.github.com/nextphp-projects/rest/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/nextphp-projects%2Frest/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":34561766,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-05-26T15:22:16.424Z","status":"online","status_checked_at":"2026-06-20T02:00:06.407Z","response_time":98,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2026-06-20T08:01:58.563Z","updated_at":"2026-06-20T08:02:00.136Z","avatar_url":"https://github.com/nextphp-projects.png","language":"PHP","funding_links":[],"categories":[],"sub_categories":[],"readme":"# NextPHP Rest Package\r\n\r\nThe [NextPHP Rest](https://packagist.org/packages/nextphp/rest) package provides powerful routing capabilities and HTTP handling for PHP developers. This package supports all RESTful methods (GET, POST, PUT, DELETE, PATCH, OPTIONS, HEAD, TRACE, CONNECT, PRI) and various response formats such as JSON, XML, HTML, TEXT, and CSV. It simplifies the creation of APIs by allowing developers to define routes and controllers using attributes, ensuring a clean and efficient codebase.\r\n\r\nThis package is part of the [NextPHP Framework](https://github.com/nextphp-projects/nextphp), a modern and lightweight PHP framework designed for performance and scalability. [NextPHP](https://nextphp.io) aims to provide a comprehensive suite of tools and libraries to streamline the development process.\r\n\r\n## Features\r\n\r\n- Support for all RESTful methods (GET, POST, PUT, DELETE, PATCH, OPTIONS, HEAD, TRACE, CONNECT, PRI)\r\n- Response formats: JSON, XML, HTML, TEXT, CSV\r\n- Attribute-based route definitions\r\n- Middleware support\r\n- Easy integration with existing projects\r\n\r\n## Installation\r\n\r\n### Installing via Composer\r\n\r\nTo install the NextPHP Rest package, you need to add it to your project using Composer.\r\n\r\n```bash\r\ncomposer require nextphp/rest\r\n```\r\n\r\n\r\n# Example Project using NextPHP Rest\r\nThis is an example project demonstrating the usage of the NextPHP Rest package, which includes routing and HTTP handling capabilities.\r\n\r\nBasic Usage\r\nDefining Routes\r\nDefine routes using attributes to map HTTP methods to controller actions.\r\n\r\n## Usage\r\n\r\n### Using Controller\r\n\r\n```php\r\n\u003c?php\r\nnamespace Example\\Controller;\r\n\r\nuse NextPHP\\Rest\\Http\\Get;\r\nuse NextPHP\\Rest\\Http\\Post;\r\nuse NextPHP\\Rest\\Http\\Put;\r\nuse NextPHP\\Rest\\Http\\Delete;\r\nuse NextPHP\\Rest\\Http\\Patch;\r\nuse NextPHP\\Rest\\Http\\RouteGroup;\r\nuse NextPHP\\Rest\\Http\\Middleware;\r\n\r\n#[RouteGroup('/api/users')]\r\nclass UserController\r\n{\r\n    #[Get('/')]\r\n    public function getAllUsers()\r\n    {\r\n        // logic to get all users\r\n    }\r\n\r\n    #[Post('/')]\r\n    public function createUser()\r\n    {\r\n        // logic to create a user\r\n    }\r\n\r\n    #[Put('/{id}')]\r\n    public function updateUser($id)\r\n    {\r\n        // logic to update a user\r\n    }\r\n\r\n    #[Delete('/{id}')]\r\n    public function deleteUser($id)\r\n    {\r\n        // logic to delete a user\r\n    }\r\n\r\n    #[Patch('/{id}')]\r\n    public function partiallyUpdateUser($id)\r\n    {\r\n        // logic to partially update a user\r\n    }\r\n}\r\n```\r\n\r\n### Advanced Entity Usage\r\n### Middleware Usage\r\n\r\nDefine middleware using attributes to apply them to routes. You can apply middleware to an entire controller class with `#[Middleware(AuthMiddleware::class)]`, or to individual routes with method-specific attributes.\r\n\r\n```php\r\n#[RouteGroup('/api')]\r\n#[Middleware(AuthMiddleware::class)]\r\nclass UserController\r\n{\r\n    #[Get('/users')]\r\n    #[Middleware(AuthMiddleware::class)]\r\n    public function getAllUsers()\r\n    {\r\n        // logic to get all users\r\n    }\r\n}    \r\n```\r\n\r\n### Generate AuthMiddleware Class\r\nAuthMiddleware handle JWT authentication check for HTTP request and response.\r\n\r\n```php\r\n\u003c?php\r\nnamespace Example;\r\n\r\nuse NextPHP\\Rest\\Http\\Request;\r\nuse NextPHP\\Rest\\Http\\Response;\r\nuse Firebase\\JWT\\JWT;\r\nuse Firebase\\JWT\\Key;\r\n\r\n/**\r\n * Class AuthMiddleware\r\n * \r\n * A simple implementation of a PSR-7 http message interface and PSR-15 http handlers.\r\n *\r\n * Middleware for handling JWT authentication.\r\n *\r\n * @package NextPHP\\Rest\\Middleware\r\n */\r\nclass AuthMiddleware\r\n{\r\n    /**\r\n     * Handles the incoming request and checks for JWT authentication.\r\n     *\r\n     * @param Request $request The HTTP request.\r\n     * @param Response $response The HTTP response.\r\n     * @param callable $next The next middleware or controller.\r\n     * @return Response The modified response.\r\n     */\r\n    public function handle(Request $request, Response $response, callable $next): Response\r\n    {\r\n        $authHeader = $request-\u003egetHeaders()['Authorization'] ?? '';\r\n        if (!$authHeader) {\r\n            return $response-\u003ewithStatus(401)-\u003ewithJSON(['error' =\u003e 'Unauthorized']);\r\n        }\r\n\r\n        list($jwt) = sscanf($authHeader, 'Bearer %s');\r\n        if (!$jwt) {\r\n            return $response-\u003ewithStatus(401)-\u003ewithJSON(['error' =\u003e 'Unauthorized']);\r\n        }\r\n\r\n        try {\r\n            $decoded = JWT::decode($jwt, new Key('your-secret-key', 'HS256'));\r\n            // Token is valid, proceed with the request\r\n            return $next($request, $response);\r\n        } catch (\\Exception $e) {\r\n            return $response-\u003ewithStatus(401)-\u003ewithJSON(['error' =\u003e 'Unauthorized']);\r\n        }\r\n    }\r\n}\r\n\r\n```\r\n\r\n### Service Layer Example\r\nServices provide business logic and interact with repositories.\r\n\r\n```php\r\n\u003c?php\r\nnamespace Example;\r\n\r\n#[Service(description: 'User management service')]\r\nclass UserService\r\n{\r\n    private UserRepository $userRepository;\r\n\r\n    public function __construct(UserRepository $userRepository)\r\n    {\r\n        $this-\u003euserRepository = $userRepository;\r\n    }\r\n\r\n    #[Transactional]\r\n    public function registerUser(array $userData): User\r\n    {\r\n        $user = new User();\r\n        $user-\u003ename = $userData['name'];\r\n        $user-\u003eemail = $userData['email'];\r\n        $user-\u003epassword = password_hash($userData['password'], PASSWORD_DEFAULT);\r\n\r\n        $userArray = [\r\n            'name' =\u003e $user-\u003ename,\r\n            'email' =\u003e $user-\u003eemail,\r\n            'password' =\u003e $user-\u003epassword,\r\n        ];\r\n\r\n        $this-\u003euserRepository-\u003esave($userArray);\r\n\r\n        return $user;\r\n    }\r\n\r\n    public function getAllUsers(): array\r\n    {\r\n        return $this-\u003euserRepository-\u003efindAll();\r\n    }\r\n\r\n    public function getUserById(int $id): ?User\r\n    {\r\n        $userArray = $this-\u003euserRepository-\u003efind($id);\r\n        if (!$userArray) {\r\n            return null;\r\n        }\r\n\r\n        $user = new User();\r\n        $user-\u003eid = $userArray['id'];\r\n        $user-\u003ename = $userArray['name'];\r\n        $user-\u003eemail = $userArray['email'];\r\n        $user-\u003epassword = $userArray['password'] ?? '';\r\n\r\n        return $user;\r\n    }\r\n\r\n    public function updateUser(int $id, array $data): ?User\r\n    {\r\n        $user = $this-\u003egetUserById($id);\r\n        if (!$user) {\r\n            return null;\r\n        }\r\n\r\n        foreach ($data as $key =\u003e $value) {\r\n            if (property_exists($user, $key)) {\r\n                $user-\u003e$key = $value;\r\n            }\r\n        }\r\n\r\n        $userArray = get_object_vars($user);\r\n        $this-\u003euserRepository-\u003eupdate($id, $userArray);\r\n\r\n        return $user;\r\n    }\r\n\r\n    public function deleteUser(int $id): bool\r\n    {\r\n        $user = $this-\u003egetUserById($id);\r\n        if (!$user) {\r\n            return false;\r\n        }\r\n\r\n        $this-\u003euserRepository-\u003edelete($id);\r\n\r\n        return true;\r\n    }\r\n}\r\n```\r\n\r\n### Example Project\r\nExample for your Project Structure\r\n\r\n```code\r\nexample/\r\n├── src/\r\n│   ├── Entity/User.php\r\n│   ├── Repository/UserRepository.php\r\n│   ├── Service/UserService.php\r\n│   ├── Resource/UserResource.php\r\n├── example.php\r\n├── composer.json\r\n└── README.md\r\n```\r\n\r\n### Example or example.php\r\nTo use the NextPHP Rest package, you can create an index.php file and use the router to handle various HTTP requests. Here is an example of how you can do this:\r\n\r\nExample index.php\r\n\r\n```php\r\n\r\n\u003c?php\r\n\r\nrequire_once __DIR__ . '/vendor/autoload.php';\r\n\r\nuse NextPHP\\Rest\\DI\\Container;\r\nuse NextPHP\\Rest\\Router;\r\nuse NextPHP\\Rest\\Http\\Request;\r\nuse NextPHP\\Rest\\Http\\Response;\r\nuse NextPHP\\App\\Resource\\UserResource;\r\nuse NextPHP\\App\\Resource\\PostResource;\r\n\r\n$container = new Container();\r\n\r\n$router = new Router([\r\n    'baseUri' =\u003e '/nextphp-beta',\r\n    'allowedOrigins' =\u003e [\r\n        'http://allowed-origin.com' =\u003e ['GET', 'POST'],\r\n        'http://another-allowed-origin.com' =\u003e ['GET', 'PUT'],\r\n        '*' =\u003e ['GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'OPTIONS', 'HEAD', 'TRACE', 'CONNECT', 'PRI']\r\n    ]\r\n], $container);\r\n\r\n// DI\r\n$router-\u003eregisterRoutesFromController(UserResource::class);\r\n$router-\u003eregisterRoutesFromController(PostResource::class);\r\n\r\n$uri = $_SERVER['REQUEST_URI'];\r\n$method = $_SERVER['REQUEST_METHOD'];\r\n\r\n$request = new Request($method, $uri, getallheaders(), file_get_contents('php://input'), $_GET, $_POST);\r\n$response = new Response();\r\n\r\n$response = $router-\u003edispatch($request, $response);\r\n\r\nif ($response) {\r\n    http_response_code($response-\u003egetStatusCode());\r\n    foreach ($response-\u003egetHeaders() as $name =\u003e $value) {\r\n        header(\"$name: $value\");\r\n    }\r\n    echo $response-\u003egetBody();\r\n} else {\r\n    http_response_code(500);\r\n    echo json_encode(['error' =\u003e 'Internal Server Error', 'message' =\u003e 'No response returned.']);\r\n}\r\n\r\n```\r\n\r\n## Contributing\r\n\r\nWe welcome contributions! Here’s how you can help:\r\n\r\n- **Report Issues:** Found a bug? Report it on GitHub.\r\n- **Suggest Features:** Have an idea? Share it with us.\r\n- **Submit Pull Requests:** Improve the codebase.\r\n- **Enhance Documentation:** Help us improve our docs.\r\n\r\nFor more details, see our [Contribution Guidelines](Contributing.md).\r\n\r\n## Resources\r\n\r\n- [Official Website](https://nextphp.io)\r\n- [GitHub Repository](https://github.com/nextphp-projects/nextphp)\r\n- [Documentation](https://github.com/nextphp-projects/nextphp)\r\n\r\n## Join Our Community\r\n\r\n- **Twitter:** Follow us on [Twitter](https://twitter.com/NextPHPOfficial)\r\n- **Discord:** Join our [Discord](https://discord.gg/nextphp) community.\r\n\r\n## Contact Us\r\n\r\n- **Email:** support@nextphp.io\r\n- **Forum:** [NextPHP Mastodon](https://mastodon.social/@nextphp)\r\n- **GitHub Issues:** [NextPHP GitHub](https://github.com/nextphp-projects/nextphp/issues)\r\n\r\nThank you for being part of the NextPHP community!\r\n\r\n\u003cbr\u003e\u003cbr\u003e\u003chr\u003e\u003cbr\u003e\r\n\r\n### FAQ\r\n\r\n### Q: How do I define a route?\r\n\r\nA: Use the #[Get], #[Post], #[Put], #[Delete], #[Patch], etc. attributes to define a method as a route handler. Use #[RouteGroup] to define a common prefix for a group of routes.\r\n\r\nFor more details, see our FAQ.","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fnextphp-projects%2Frest","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fnextphp-projects%2Frest","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fnextphp-projects%2Frest/lists"}