Giter VIP home page Giter VIP logo

laravel-request-docs's Introduction

Laravel Request Docs

The Hassle-Free automatic API documentation generation for Laravel.
A Swagger alternative.
Supports Open API 3.0.0

Try latest DEMO!

CI Node CI PHP codecov Latest Stable Version Total Downloads License

Fast Install on any Laravel Project

Hassle Free Auto Generate API Documentation for request rules and parameters

Analyze Inbuilt SQL query time analyzer, response time and headers output.

Supports Postman and OpenAPI 3.0.0 exports.

Features

  • Light and Dark mode
  • Automatic rules fetching from injected Request and by regexp
  • Automatic routes fetching from Laravel Routes
  • Support for Laravel logs
  • Support for SQL query and query time
  • Support for HTTP response time and memory consumption
  • Support for Authorization Headers
  • Support for File uploads
  • Support for Eloquents events
  • Display extra documentation using markdown
  • Saves history previous requests
  • Added filters to sort, group and filter routes by methods, controllers, middlewares, routes
  • Export Laravel API, routes, rules and documentation to Postman and OpenAPI 3.0.0

Read on Medium

Automatically generate API documentation for Laravel without writing annotations.

Read more: https://medium.com/web-developer/laravel-automatically-generate-api-documentation-without-annotations-a-swagger-alternative-e0699409a59e

Requirements

Lang Versions
PHP 7.4 or 8.0 or 8.1 or 8.2
Laravel 6.* or 8.* or 9.* or 10.*

Installation

You can install the package via composer:

composer require rakutentech/laravel-request-docs

You can publish the config file with:

php artisan vendor:publish --tag=request-docs-config
php artisan route:cache

# Optional publish assets
# php artisan vendor:publish --tag=request-docs-assets

(optional) Add the following middleware to your API, so that the SQL logs and model events are captured.

app/Http/Kernel.php

        'api' => [
            ...
            \Rakutentech\LaravelRequestDocs\LaravelRequestDocsMiddleware::class,
            ... and so on

Usage

Dashboard

View in the browser on /request-docs/

Design pattern

For this plugin to work, you need to follow the design pattern by injecting the request class inside the controller. For extra documentation you can use markdown inside your controller method as well.

Design pattern

Screenshots

Dark and Light Modes

  • Uses local storage to save the history of previous requests and request headers.
  • Request, SQL, response and events timeline below:

Settings to sort, group and filter

Extra documentation

You can write extra documentation in markdown using @lrd in the PHPDoc on the rules method of the Request classes and on the controller methods.
This will then be rendered as HTML on the dashboard.
Documentation defined on the controller method is appended below documentation defined on the rules method.
Example of using it in the controller:

    /**
     * @lrd:start
     * # Hello markdown
     * Free `code` or *text* to write documentation in markdown
     * @lrd:end
     */
    public function index(MyIndexRequest $request): Resource
    {

Extra parameters

You define extra parameters using @LRDparam.
You can use @LRDparam in PHPDoc on both the rules methods and the controller methods.
You can also overwrite rules using @LRDparam. Meaning, when rules are defined in the rules method, you can overwrite those rules using @LRDparam in the PHPDoc above the rules method. And you can overwrite those rules using @LRDparam in a PHPDoc on the controller methods.
So, the precedence is Controller method PHPDoc < Rules method PHPDoc < Rules method values.

    /**
     * @LRDparam username string|max:32
     * // either space or pipe
     * @LRDparam nickaname string|nullable|max:32
     * // override the default response codes
     * @LRDresponses 200|422
     */
    public function index(MyIndexRequest $request): Resource
    {

Response codes

Without explicitly declaring response codes, all routes are documented to return any of the response codes defined in the request-docs.php default_responses configuration.
However, using @LRDresponse 200|422 (spaces or pipes) within the PHPDoc on your controller methods, you are able to explicitly define what status codes can be returned by the server.

Configuration

Please view the request-docs.php config file to see how you can customise your experience.

Testing

./vendor/bin/phpunit

Linting

./vendor/bin/phpcs --standard=phpcs.xml --extensions=php --ignore=tests/migrations config/ src/

Fixing lints

./vendor/bin/php-cs-fixer fix src/
./vendor/bin/php-cs-fixer fix config/

Star History

Star History Chart

Changelog

  • Initial Release
  • v1.9 Added improvements such as status code, response headers, custom request headers and fixed issues reported by users
  • v1.10 Show PHP memory usage, gzip encoding fix
  • v1.12 Bug fix of id, and Laravel 9 support
  • v1.13 Laravel 9 support
  • v1.15 Adds Filter and fall back to regexp upon Exception
  • v1.17 Do not restrict to FormRequest
  • v1.18 Fix where prism had fixed height. Allow the text area resize.
  • v1.18 Updated UI and pushed unit tests
  • v1.19 Exception -> Throwable for type error
  • v1.20 Feature support open api 3.0.0 #10
  • v1.21 Ability to add custom params
  • v1.22 Boolean|File|Image support
  • v1.22 Boolean|File|Image support
  • v1.23 Bug fix for LRD doc block #76
  • v1.27 A few fixes on width and added request_methods
  • v2.0 UI Renewal to React Static
    • @QAParam is now @LRDparam
    • No special changes for users, upgrade to v2.x as usual
    • Upgrading users will need to republish config
  • v2.1 UI - adds search bar and few alignment fixes on table
  • v2.2 PHP 8.1 and 8.2 support added - Groupby enabled for routes and controllers
  • v2.3 Bug fix for local storage (tabs) and full UI refactored after alpha
  • v2.4 Show version on navbar and curl is using ace editor
  • v2.5 Groupby final fix and local storage clear button. Other UI refactor
  • v2.6 File uploads
  • v2.7 Show activity on Eloquent models
  • v2.8 Show full activity on Eloquent models
  • v2.13 Bug fixes, and nested params support
  • v2.14 Adds path params support
  • v2.16 Top Navbar is fixed
  • v2.19 Publish _astro assets
  • v2.25 laravel-request-docs:export command to export
  • v2.28 Allow extra documentation to be defined on the rules method of the Request class. By @Ken-vdE
  • v2.31 Customized title, vup js and PHP to latest. Customized headers. Save response history.

Contributors

laravel-request-docs's People

Contributors

abodnar avatar asurcodes avatar brel-pro avatar cdmathukiya avatar daprezjer avatar davlet42 avatar dedmytro avatar digitall-it avatar eclips16 avatar farshadfakhar avatar giraz82 avatar github-actions[bot] avatar hafijul233 avatar justinphan1992 avatar ken-vde avatar kevincobain2000 avatar kitloong avatar laravel-shift avatar mdhesari avatar mello21century avatar mizouzie avatar nikolarhristov avatar nimah79 avatar plong-wasin avatar pocketnest-erik avatar rawahamid avatar souravdutt avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

laravel-request-docs's Issues

Feature request: Sorting routes in generated HTML

Hello!

I am testing your package with some Laravel projects and I have a question for the generated route list. For now, I am using a random Laravel with default config of your package.

In my generated HTML, the routes are sorted by their method. Is it possible to sort them by name/prefix, or I am doing something wrong?

Thanks!

Add a pre class to load fake user and/or seed data conditions for docs to generate

Related to #38

When rules in the request class throw exceptions, the docs currently skip scanning that route.
We have made previous attempts to fetch rules via reg exp, but that way is too tricky and has high chances to produce wrong results.

Fetching of the rule may fail because of preconditions such as #8 or methods such as findOrFail.

The solution is to provide a middleware class that the user can configure - where pre-conditions such as load Auth fake user, or seed data can be added.

Support response type base on returned Resource

Is any type of return properties list supported or we should execute an example request to be able to see the response format ?
I am using ...Resource classes (something like below) to be returned from each controller method response so the returned keys could be extracted the same way as they are for Request classes:

<?php

namespace App\Http\Resources;

use Illuminate\Http\Resources\Json\JsonResource;

class ClientResource extends JsonResource
{
    public function toArray($request): array
    {
        return [
            'id' => $this->id,
            'displayName' => $this->display_name,
        ];
    }
}

getting 404 on request-docs

In my dev server, everything works great, but I'm running php 7.4. In my production servicer, we have php 8.1.3 and I'm getting 404 on /request-docs/

Could it be the php version?

Create separate docs based on scopes

What a nice package, I am enjoying it, But one little thing I want to have is:
I have different API scopes in my project, some of them are for interacting with the front app, some of them are for mobile and etc.

The package should have a config for separating scopes and for a big project it is better to categorize APIs.

Support for Sanctum

Can you add Support form sanctum middleware "auth:sanctum"? i want to add Bearer Header

Missing sql queries

Hello! Maybe it's not an issue, but why don't I have sql displayed when querying?
Снимок экрана 2022-05-17 в 21 35 13

Endpoint duplicated

If use API Resources Route, the Endpoint duplicated the Update Method Endpoint will appear duplicated in /request-docs.

Feature request - JSON object structure validation

Good morning

Just a feature request for the JSON request structure. I like the way the generation for API documentation grabs the request rules.

Would like to just see it in JSON object format.

from this:

{ "dealership.dealership_group_id": "", "company.brand_name": "", "company.trading_name": "", "company.registered_name": "", "company.reg_no": "", "company.vat_no": "", "company.email": "", "company.telephone": "", "company.website_url": "", "address.unit_no": "", "address.line1": "", "address.line2": "", "address.post_code": "", "address.province": "", "address.country": "" }

To this:

{ "dealership":{ "dealership_group_id":"" }, "company":{ "brand_name":"", "trading_name":"", "registered_name":"", "reg_no":"", "vat_no":"", "email":"", "telephone":"", "website_url":"" }, "address":{ "unit_no":"", "line1":"", "line2":"", "post_code":"", "province":"", "country":"" } }

Dont output type in rules

If you have a rule like "string|required|min:1" then "string" also appears in rules. I think its enough if you can see it in the type, its crystal clear that then string is in the rules

ErrorException

Trying to get property 'id' of non-object
image
Call to a member function hasRole() on null
image

Hi, I apologize of course, but I could not find a solution to this problem, can you tell me how to fix it

Feature: Please filter by route and method.

I have two routes - mobile and back office. I would like them to be grouped by route name and method when filtering. It would be nice to add a separation between these methods, but I understand that this is a rare case.

//RouteServiceProvider::class

$this->routes(function () {
    Route::prefix('backoffice/api/v1')
        ->middleware('backoffice.api')
        ->name('backoffice.api.v1.')
        ->namespace($this->namespace)
        ->group(base_path('routes/api/backoffice/v1.php'));
    
    Route::prefix('mobile/api/v1')
        ->middleware('mobile.api')
        ->name('mobile.api.v1.')
        ->namespace($this->namespace)
        ->group(base_path('routes/api/mobile/v1.php'));
    });
}

Not getting a Response on LRD

Hello,

I was testing this LRD and its very simple to start, thanks for that. Unfortunately when i run the endpoints it gives me a 200 but i see no response body.
This is all i see after running the endpoint with the Bearer already filled that i have to get from PostMan because i can not get a response from the login:

image
image

I am returning resources, but i tried returning only an array and it did not work.

Am I doing something wrong? This is working perfectly fine in swagger if I do the whole process of creating the annotations.

Thank you

Read and Identity Enums

Enums are allowed as a query parameter - it would be great if it could read this and identify the possible routes based on this.

Moreover, generally identifying the data type of the route param would be great.

For example; for uuids:
/users/{record} => record: string

For autonumber ids:
/users/{record} => record: integer

Where model is an enum, record is string:
/{model}/{record} => model: enum [users, projects, tasks, quotes]

Probably displayed as a table, such as:

Query Params:

Field    | Type   | Data
===================================
model    | enum   | users, projects, tasks, quotes
-----------------------------------
record   | string |
-----------------------------------

Ignoring of request headers

If i use the url and try authenticate via the docs i always get a error as it was the CSRF token which is not needed for the sanctum api request.

If i export to postman and click the button to post to auth then i get the response i am looking for..
Screenshot 2022-04-26 at 15 41 31
Screenshot 2022-04-26 at 15 44 09

If i try postman i get the correct response:
Screenshot 2022-04-26 at 15 45 51

method_exist(rules) instaed instanceof FormRequest test

Hi,
I'm a developer for a laravel api and i want build docs with your packages.

It's more important to open the possibility to test method_exist(rules) instaed instanceof FormRequest test.

I've RequestClasses that are not inherited from FormRequest class. It's important to test parameter instance has rules() method.

Define path variable

Hello all,

I am having problems defining the variable that we pass in the URL:

image

Any idea how to define it?

Thank you

Support Array output

If you have a parameter like a billing address you cant make an array "billing" containing values like "firstname" and "lastname". Instead you need to need make "billing_firstname" and "billing_lastname"

Error: Call to undefined method ReflectionUnionType::getName()

Having laravel 8.5.8 installed and LRD in 1.22 running into the error:

$ php artisan lrd:generate

   Error

  Call to undefined method ReflectionUnionType::getName()

  at C:\Users\****\****\vendor\rakutentech\laravel-request-docs\src\LaravelRequestDocs.php:126
    122▕             foreach ($params as $param) {
    123▕                 if (!$param->getType()) {
    124▕                     continue;
    125▕                 }
  ➜ 126▕                 $requestClassName = $param->getType()->getName();
    127▕                 $requestClass = null;
    128▕                 try {
    129▕                     $requestClass = new $requestClassName();
    130▕                 } catch (Throwable $th) {

  1   C:\Users\****\****\vendor\rakutentech\laravel-request-docs\src\LaravelRequestDocs.php:18
      Rakutentech\LaravelRequestDocs\LaravelRequestDocs::appendRequestRules()

  2   C:\Users\****\****\vendor\rakutentech\laravel-request-docs\src\Commands\LaravelRequestDocsCommand.php:30
      Rakutentech\LaravelRequestDocs\LaravelRequestDocs::getDocs()

php artisan route:list is emitting every single route correctly. I haven't changed anything in config, project etc.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.