PHPackages                             shangab/slim-swagger - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [API Development](/categories/api)
4. /
5. shangab/slim-swagger

ActiveLibrary[API Development](/categories/api)

shangab/slim-swagger
====================

Automatic SWAGGER for slim projects, wroks as middleware.

1.9.0(1y ago)4132↓100%MITPHP

Since Jan 13Pushed 1y ago1 watchersCompare

[ Source](https://github.com/shangab/slim-swagger)[ Packagist](https://packagist.org/packages/shangab/slim-swagger)[ RSS](/packages/shangab-slim-swagger/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (4)Dependencies (2)Versions (5)Used By (0)

Slim Swagger Middleware
=======================

[](#slim-swagger-middleware)

This is a Slim PHP middleware that automatically generates and serves Swagger (OpenAPI) documentation for your Slim PHP API routes. It supports dynamic route scanning, including GET, POST, PUT, PATCH, and DELETE methods, and generates detailed documentation without requiring external annotation libraries. This project was created for a project I am working on in `php`. I used to do backend with `Python FatAPI` or `.NET`, which both have swagger UI embeded in them, out of the box. However in `php` swagger it is tricky and time consuming.

I wanted the same automatic swagger in `php` in my new project but the easiest way I found is using external packages such as `zircote/swagger-php` which requires a lot of annotations if I got it right. I loved the fact that `slim-php` is light, powerful and scalable, Therefore, I started to build this middleware. The first version, `tag`, was built in a hurry in a single day, but the future roadmap will increase the middleware power and flexibility.

All the best wishes, use, recommend, star, fork, contribute, spread and enjoy it.

Features
--------

[](#features)

- **Automatic Swagger generation**: Scans all Slim routes and generates OpenAPI documentation on the fly.
- **Supports multiple HTTP methods**: Handles GET, POST, PUT, PATCH, DELETE, and more.
- **No external annotations**: Does not rely on any library or any third-party annotation libraries like `zircote/swagger-php`.
- **Customizable**: Easily extendable to add custom parameters, request bodies, and responses.
- **MIT License**: Open-source and free to use under the MIT License.

Requirements
------------

[](#requirements)

1. php 8.2
2. "slim/slim": "^4.9"
3. "slim/psr7": "^1.5"

[![image](swagger.png)](swagger.png)

The classes to be used
----------------------

[](#the-classes-to-be-used)

We now have three classes:

1. `ShangabSlimSwagger` The middleware for the swagger openapi and ui.
2. `ShangabJWTAuth` The middleware for authenticated routes or group of routes.
3. `ShangabJWTUtil` A utility class that have four public functions, to handle authorization using `shangab/slim-swagger` you should use this utility class:
    1. `public function createToken($userData): string` Given a user json object it will generates JWT token.
    2. `public function verifyToken(): mixed` This will verify the header `Authorization` bearer token and returns the user data or false if not authenticated.
    3. `public function getTempPassword($length = 5): string` This fuction will return a temporary password, default length is 5.
    4. `public function getHash256($text): string` This function takes any text and gives a 256 hash code.

Step 1: Installation
--------------------

[](#step-1-installation)

You can install this middleware in your Slim project via Composer from `https://packagist.org/`.

```
composer require shangab/slim-swagger
```

### Step 2: How to use `ShangabJWTUtil`

[](#step-2-how-to-use-shangabjwtutil)

Use this class to:

1. Create `JWT` tokens for logged-in users.
2. Verify that the user has valid tokens.
3. Generate temporary passwords.
4. Hash text as you see fit.

To use the `ShangabJWTUtil` class in your code, see below example:

```
use Shangab\Middleware\ShangabJWTUtil;

$jwtUtil = new ShangabJWTUtil;
```

2.1 To crate a `JWT` token:

```
$user =[LOGIN THE USER WITH YOUR CONTROLLER CODE];
$jwtToken = $jwtUtil->createToken($user);
```

2.2 To verify a `JWT` token, though the middleware does it for you, but f you want to:

```
$verified = $jwtUtil->verifyToken(); // token will be read from the request headers.
```

2.3 To generate a temporary password:

```
$password = $jwtUtil->getTempPassword(8);
```

2.4 To hash any text:

```
$hashed = $jwtUtil->getHash256("Hello World!");
```

### Step 3: How to use The Middleware

[](#step-3-how-to-use-the-middleware)

To use the middleware follow the code below, declare the `ShangabSlimSwagger` middleware and add it to your app in `index.php`: First list all the protected groups of endpoints or endpoints, then list the un-protected ones.

```
use Shangab\Middleware\ShangabSlimSwagger;
use Shangab\Middleware\ShangabJWTAuth;
```

```
$app = AppFactory::create();

$app->add(new ShangabSlimSwagger($app, 'Shangab Slim Swagger', '1.0.1', 'Api for Shangab Slim Swagger.'));

// Protected endpoins same group: "users"
$app->group('/users', function ($app) use ($container) {
    $app->post('/add', function (Request $request, Response $response, $args) use ($container) {
        $body = $request->getBody()->getContents();
        $user = json_decode($body, true);
        $container['data']['users'][] = $user;
        $users = $container['data']['users'];
        $response->getBody()->write(json_encode(['status' => true, 'message' => 'User addded', 'users' => $users]));
        return $response->withHeader('Content-Type', 'application/json');
    });
    $app->put('/update', function (Request $request, Response $response, $args) use ($container) {
        $body = $request->getBody()->getContents();
        $user = json_decode($body, true);
        $key = array_search($user['id'], array_column($container['data']['users'], 'id'));
        $container['data']['users'][$key] = $user;
        $users = $container['data']['users'];
        $response->getBody()->write(json_encode(['status' => true, 'message' => 'User updated', 'users' => $users]));
        return $response->withHeader('Content-Type', 'application/json');
    });
    $app->delete('/delete/{id}', function (Request $request, Response $response, $args) use ($container) {
        $id = $args['id'];
        $users = array_values(array_filter($container['data']['users'], function ($user) use ($id) {
            return $user['id'] != $id;
        }));
        $response->getBody()->write(json_encode(['status' => true, 'message' => 'User deleted', 'users' => $users]));
        return $response->withHeader('Content-Type', 'application/json');
    });
})->add(new ShangabJWTAuth($app));

// All routes above this middleware will apply ShangabJWTAuth middleware protected routes.
// Below routes will not be protected by ShangabJWTAuth middleware.

// UnProtected endpoins same group: "users"
$app->group('/users', function ($app) use ($container) {
    $app->get('/staff', function (Request $request, Response $response, $args) use ($container) {
        $users = array_values(array_filter($container['data']['users'], function ($user) {
            return $user['type'] == 'staff';
        }));
        $response->getBody()->write(json_encode($users));
        return $response->withHeader('Content-Type', 'application/json');
    });
    $app->get('/client', function (Request $request, Response $response, $args) use ($container) {
        $users = array_values(array_filter($container['data']['users'], function ($user) {
            return $user['type'] == 'client';
        }));
        $response->getBody()->write(json_encode($users));
        return $response->withHeader('Content-Type', 'application/json');
    });
    $app->get('/all', function (Request $request, Response $response, $args) use ($container) {
        $users = $container['data']['users'];
        $response->getBody()->write(json_encode($users));
        return $response->withHeader('Content-Type', 'application/json');
    });
});

$app->run();
```

### Please avoid using route names `openapi` and `docs`

[](#please-avoid-using-route-names-openapi-and-docs)

I use these two routes and serve them before the `$app` routes, `openapi` returns the OpenAPI Specs, while `docs` route returns the swagger UI shown above.

###  Health Score

29

—

LowBetter than 60% of packages

Maintenance45

Moderate activity, may be stable

Popularity15

Limited adoption so far

Community7

Small or concentrated contributor base

Maturity41

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~6 days

Total

4

Last Release

462d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/a2777e568d9e0eafac3ab578efb0a389986819dab505c9a4633a75059f5e97bf?d=identicon)[shangab](/maintainers/shangab)

---

Top Contributors

[![shangab](https://avatars.githubusercontent.com/u/575789?v=4)](https://github.com/shangab "shangab (9 commits)")

### Embed Badge

![Health badge](/badges/shangab-slim-swagger/health.svg)

```
[![Health](https://phpackages.com/badges/shangab-slim-swagger/health.svg)](https://phpackages.com/packages/shangab-slim-swagger)
```

###  Alternatives

[showdoc/showdoc

ShowDoc is a tool greatly applicable for an IT team to share documents online

12.8k7.0k](/packages/showdoc-showdoc)[docler-labs/codeception-slim-module

Codeception Module for Slim framework.

13178.0k1](/packages/docler-labs-codeception-slim-module)[b13/slimphp-bridge

Provides a middleware for registering Slim PHP applications within TYPO3 Frontend Sites

2047.2k1](/packages/b13-slimphp-bridge)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
