Do not speak Portuguese? Translate this site with Google or Bing Translator
Laravel API Documentation Generator with Scribe

Posted on: March 30, 2022 11:59 AM

Posted by: Renato

Views: 2165

# laravel scribe knuckles


## Laravel API Documentation Generator with Scribe | Laravel API Server

## Laravel permissions

sudo chgrp -R www-data storage bootstrap/cache ; sudo chmod -R ug+rwx storage bootstrap/cache

sudo chown -R $USER:www-data * ; sudo chmod -R ug+rwx storage bootstrap/cache

A tool to automatically fix PHP code style


composer require friendsofphp/php-cs-fixer


Execute this command to fix all files

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

https://memorandum.ewilan-riviere.com/development/frameworks/laravel/setup-dependencies/

composer require knuckleswtf/scribe
php artisan vendor:publish --tag=scribe-config
composer show knuckleswtf/scribe
php artisan scribe:generate

If you're using Sanctum with scribe, you have to set :

config/scribe.php

'use_csrf' => true, //default false

Mais sobre a instalação e configuração

Scribe: Your Ultimate Companion for Laravel API Documentation

Scribe is a powerful tool that can save you countless hours of manual documentation work. By following this guide, you can easily set up Scribe in your Laravel project, configure it to match your needs, and generate beautiful, up-to-date API documentation with minimal effort.

https://demo.scribe.knuckles.wtf/

In the world of modern web development, APIs play a crucial role in facilitating communication between different systems and applications. As APIs grow in complexity, documenting them becomes increasingly important for developers to understand how to interact with them effectively. Laravel, one of the most popular PHP frameworks, offers a powerful tool called Scribe for generating comprehensive API documentation.

Scribe is an open-source package developed by the team at Knuckles.wtf. It leverages Laravel’s powerful routing and middleware system to generate beautiful and interactive documentation for your API. In this blog post, we’ll explore how to set up Scribe in your Laravel project, configure it to suit your needs, and generate documentation that will make your life easier.

Setting up Scribe in Your Laravel Project

Before we dive into the configuration details, let’s start by installing Scribe in your Laravel project. Open your terminal, navigate to your project’s root directory, and run the following command:

composer require --dev knuckleswtf/scribe

This command will install Scribe as a development dependency in your project. Once the installation is complete, you need to publish Scribe’s configuration file by running:

php artisan vendor:publish --provider="Knuckles\Scribe\ScribeServiceProvider"

This command will create a new file named scribe.php in your project's config directory. You can now customize the configuration according to your needs.

Configuring Scribe

Scribe offers a wide range of configuration options that allow you to tailor the generated documentation to your specific requirements. The configuration file we published earlier (config/scribe.php) is where you'll make most of these customizations.

Let’s take a look at some of the essential configuration options:

<?php

return [
// The title of your documentation
'title' => 'My API Documentation',

// A short description of your API
'description' => 'This is the documentation for my awesome API.',

// The base URL for your API
'base_url' => env('APP_URL'),

// The routes to include in the documentation
'routes' => [
[
'match' => [
'prefixes' => ['api/*'],
'domains' => ['*'],
],
'exclude' => [
'api/documentation',
],
],
],

// ...
];

In this example, we’ve set the title, description, and base URL for our documentation. We’ve also configured Scribe to include all routes prefixed with api/* and exclude the api/documentation route.

You can find more configuration options in the config/scribe.php file, such as authentication settings, example languages, and options for generating Postman collections and OpenAPI specifications.

Generating Documentation

Once you’ve configured Scribe to your liking, you can generate the documentation by running the following command:

php artisan scribe:generate

This command will analyze your application’s routes, controllers, and request/response transformers to generate comprehensive documentation for your API. Depending on your project’s size and complexity, this process may take some time to complete.

If you’ve configured Scribe to generate a static HTML page ('type' => 'static'), the generated documentation will be saved in the public/docs directory by default. You can then access the documentation by visiting http://your-app-url/docs in your web browser.

Alternatively, if you’ve configured Scribe to generate a Blade view ('type' => 'laravel'), the documentation will be accessible via a route defined by Scribe. By default, this route is /docs, but you can change it in the configuration file.

Tips and Notes

  • Documenting Your Routes: Scribe relies heavily on DocBlock comments and annotations to generate documentation. Make sure to document your routes, controllers, and request/response transformers using appropriate DocBlock comments and annotations for optimal results.
  • Generating Example Responses: Scribe can generate example responses for your API endpoints based on your application’s models and transformers.
  • Regenerating Documentation: As you make changes to your API, remember to regenerate the documentation by running php artisan scribe:generate again.

How to Document a Laravel REST API

Last Updated on November 30, 2022

When building a REST API it is almost a given that you have to create documentation for the API. This allows other developers to consume your API with ease.

Developers praise most popular software such as Stripe for having good documentation and this has resulted in Stripe being used by a lot of developers.

Good documentation can be a powerful tool for business especially if a company is dependent on other developers building on top of their platform.

Platforms such as Shopify have invested a lot of effort in providing good documentation to developers which then causes a ripple effect of attracting more developers to build their solutions on top of Shopify.

In this tutorial, we will cover how to document your Laravel REST API.

I will try and document the REST API I created earlier. You can find its article here.

Features of a Good API Documentation

A well-documented API should have the following:

  • An Introduction/Explanation of what the API does
  • An Authentication Guide
  • A List of the Resources Available for Consuming.
  • Examples of requests and their corresponding responses with descriptive messages, errors etc.
  • Code Snippets of popular languages

Your API Documentation can be static or interactive depending on your needs but should have these features above in order to be somewhat complete.

Some other things you might add are:

  • Changelog
  • Provide Tutorials
  • Separate Documentation by API Version.
  • Terms of Use and Rate Limiting
  • SDK examples if available.

A bonus tip is to add curl requests as part of the Code Snippets to allow developers whose language is not featured to easily understand the format of the Requests.

Luckily for us, there are two popular packages that can help generate API documentation with minimal effort; Swagger(OpenAPI) and Scribe.

In this tutorial, I will use Scribe to generate documentation for my API.

If you want to learn how to document your API using Swagger(OpenAPI), you can read this article.

How to Document a REST API in Laravel

The scribe package allows us to create well-optimized API Documentation with little to no effort. It provides Code Snippets and a bare-bone skeleton which we can use to our advantage to generate REST API documentation in a fast and easy way.

Let’s get started.

Install Scribe

The first step is to install the Scribe Package

composer require --dev knuckleswtf/scribe

Publish Configurations

We can then publish the package’s configurations

php artisan vendor:publish --tag=scribe-config

This will create a scibe.php file in the config folder.

Update the configuration file.

There are a few things we need to update in the config/scribe.php file. The first one is the title.

You can change it or leave it as is and it will use the Application’s default name.

The next one is the description. You can provide a short description of your API.

The next configuration is the base url. Scribe will use the default App URL unless you specify one. I will leave mine as the default app URL.

Other Configurations that can be changed include auth, type and logo. You can customize the configurations to match your API.

My final configuration file resembles the one below.

// config/scribe.php

<?php

use Knuckles\Scribe\Extracting\Strategies;

return [

    'theme' => 'default',

    /*
     * The HTML <title> for the generated documentation. If this is empty, Scribe will infer it from config('app.name').
     */
    'title' => 'Laravel REST API',

    /*
     * A short description of your API. Will be included in the docs webpage, Postman collection and OpenAPI spec.
     */
    'description' => 'A simple REST API in Laravel',

    /*
     * The base URL displayed in the docs. If this is empty, Scribe will use the value of config('app.url').
     */
    'base_url' => null,

    /*
     * Tell Scribe what routes to generate documentation for.
     * Each group contains rules defining which routes should be included ('match', 'include' and 'exclude' sections)
     * and settings which should be applied to them ('apply' section).
     */
    'routes' => [
        [
            /*
             * Specify conditions to determine what routes will be a part of this group.
             * A route must fulfill ALL conditions to be included.
             */
            'match' => [
                /*
                 * Match only routes whose paths match this pattern (use * as a wildcard to match any characters). Example: 'users/*'.
                 */
                'prefixes' => ['api/*'],

                /*
                 * Match only routes whose domains match this pattern (use * as a wildcard to match any characters). Example: 'api.*'.
                 */
                'domains' => ['*'],

                /*
                 * [Dingo router only] Match only routes registered under this version. Wildcards are not supported.
                 */
                'versions' => ['v1'],
            ],

            /*
             * Include these routes even if they did not match the rules above.
             * The route can be referenced by name or path here. Wildcards are supported.
             */
            'include' => [
                // 'users.index', 'healthcheck*'
            ],

            /*
             * Exclude these routes even if they matched the rules above.
             * The route can be referenced by name or path here. Wildcards are supported.
             */
            'exclude' => [
                // '/health', 'admin.*'
            ],

            /*
             * Settings to be applied to all the matched routes in this group when generating documentation
             */
            'apply' => [
                /*
                 * Additional headers to be added to the example requests
                 */
                'headers' => [
                    'Content-Type' => 'application/json',
                    'Accept' => 'application/json',
                ],

                /*
                 * If no @response or @transformer declarations are found for the route,
                 * Scribe will try to get a sample response by attempting an API call.
                 * Configure the settings for the API call here.
                 */
                'response_calls' => [
                    /*
                     * API calls will be made only for routes in this group matching these HTTP methods (GET, POST, etc).
                     * List the methods here or use '*' to mean all methods. Leave empty to disable API calls.
                     */
                    'methods' => ['GET'],

                    /*
                     * Laravel config variables which should be set for the API call.
                     * This is a good place to ensure that notifications, emails and other external services
                     * are not triggered during the documentation API calls.
                     * You can also create a `.env.docs` file and run the generate command with `--env docs`.
                     */
                    'config' => [
                        'app.env' => 'documentation',
                        // 'app.debug' => false,
                    ],

                    /*
                     * Query parameters which should be sent with the API call.
                     */
                    'queryParams' => [
                        // 'key' => 'value',
                    ],

                    /*
                     * Body parameters which should be sent with the API call.
                     */
                    'bodyParams' => [
                        // 'key' => 'value',
                    ],

                    /*
                     * Files which should be sent with the API call.
                     * Each value should be a valid path (absolute or relative to your project directory) to a file on this machine (but not in the project root).
                     */
                    'fileParams' => [
                        // 'key' => 'storage/app/image.png',
                    ],

                    /*
                     * Cookies which should be sent with the API call.
                     */
                    'cookies' => [
                        // 'name' => 'value'
                    ],
                ],
            ],
        ],
    ],

    /*
     * The type of documentation output to generate.
     * - "static" will generate a static HTMl page in the /public/docs folder,
     * - "laravel" will generate the documentation as a Blade view, so you can add routing and authentication.
     */
    'type' => 'laravel',

    /*
     * Settings for `static` type output.
     */
    'static' => [
        /*
         * HTML documentation, assets and Postman collection will be generated to this folder.
         * Source Markdown will still be in resources/docs.
         */
        'output_path' => 'public/docs',
    ],

    /*
     * Settings for `laravel` type output.
     */
    'laravel' => [
        /*
         * Whether to automatically create a docs endpoint for you to view your generated docs.
         * If this is false, you can still set up routing manually.
         */
        'add_routes' => true,

        /*
         * URL path to use for the docs endpoint (if `add_routes` is true).
         * By default, `/docs` opens the HTML page, `/docs.postman` opens the Postman collection, and `/docs.openapi` the OpenAPI spec.
         */
        'docs_url' => '/docs',

        /*
         * Directory within `public` in which to store CSS and JS assets.
         * By default, assets are stored in `public/vendor/scribe`.
         * If set, assets will be stored in `public/{{assets_directory}}`
         */
        'assets_directory' => null,

        /*
         * Middleware to attach to the docs endpoint (if `add_routes` is true).
         */
        'middleware' => [],
    ],

    'try_it_out' => [
        /**
         * Add a Try It Out button to your endpoints so consumers can test endpoints right from their browser.
         * Don't forget to enable CORS headers for your endpoints.
         */
        'enabled' => true,

        /**
         * The base URL for the API tester to use (for example, you can set this to your staging URL).
         * Leave as null to use the current app URL (config(app.url)).
         */
        'base_url' => null,

        /**
         * Fetch a CSRF token before each request, and add it as an X-XSRF-TOKEN header. Needed if you're using Laravel Sanctum.
         */
        'use_csrf' => false,

        /**
         * The URL to fetch the CSRF token from (if `use_csrf` is true).
         */
        'csrf_url' => '/sanctum/csrf-cookie',
    ],

    /*
     * How is your API authenticated? This information will be used in the displayed docs, generated examples and response calls.
     */
    'auth' => [
        /*
         * Set this to true if any endpoints in your API use authentication.
         */
        'enabled' => true,

        /*
         * Set this to true if your API should be authenticated by default. If so, you must also set `enabled` (above) to true.
         * You can then use @unauthenticated or @authenticated on individual endpoints to change their status from the default.
         */
        'default' => false,

        /*
         * Where is the auth value meant to be sent in a request?
         * Options: query, body, basic, bearer, header (for custom header)
         */
        'in' => 'bearer',

        /*
         * The name of the auth parameter (eg token, key, apiKey) or header (eg Authorization, Api-Key).
         */
        'name' => 'token',

        /*
         * The value of the parameter to be used by Scribe to authenticate response calls.
         * This will NOT be included in the generated documentation.
         * If this value is empty, Scribe will use a random value.
         */
        'use_value' => env('SCRIBE_AUTH_KEY'),

        /*
         * Placeholder your users will see for the auth parameter in the example requests.
         * Set this to null if you want Scribe to use a random value as placeholder instead.
         */
        'placeholder' => '<token>',

        /*
         * Any extra authentication-related info for your users. For instance, you can describe how to find or generate their auth credentials.
         * Markdown and HTML are supported.
         */
        'extra_info' => 'You can retrieve your token by logging in to your account.',
    ],

    /*
     * Text to place in the "Introduction" section, right after the `description`. Markdown and HTML are supported.
     */
    'intro_text' => <<<INTRO
This documentation aims to provide all the information you need to work with our API.

<aside>As you scroll, you'll see code examples for working with the API in different programming languages in the dark area to the right (or as part of the content on mobile).
You can switch the language used with the tabs at the top right (or from the nav menu at the top left on mobile).</aside>
INTRO,

    /*
     * Example requests for each endpoint will be shown in each of these languages.
     * Supported options are: bash, javascript, php, python
     * To add a language of your own, see https://scribe.knuckles.wtf/laravel/advanced/example-requests
     *
     */
    'example_languages' => [
        'bash',
        'javascript',
        'php',
        'python'
    ],

    /*
     * Generate a Postman collection (v2.1.0) in addition to HTML docs.
     * For 'static' docs, the collection will be generated to public/docs/collection.json.
     * For 'laravel' docs, it will be generated to storage/app/scribe/collection.json.
     * Setting `laravel.add_routes` to true (above) will also add a route for the collection.
     */
    'postman' => [
        'enabled' => true,

        /*
         * Manually override some generated content in the spec. Dot notation is supported.
         */
        'overrides' => [
            // 'info.version' => '2.0.0',
        ],
    ],

    /*
     * Generate an OpenAPI spec (v3.0.1) in addition to docs webpage.
     * For 'static' docs, the collection will be generated to public/docs/openapi.yaml.
     * For 'laravel' docs, it will be generated to storage/app/scribe/openapi.yaml.
     * Setting `laravel.add_routes` to true (above) will also add a route for the spec.
     */
    'openapi' => [
        'enabled' => true,

        /*
         * Manually override some generated content in the spec. Dot notation is supported.
         */
        'overrides' => [
            // 'info.version' => '2.0.0',
        ],
    ],

    'groups' => [
        /*
         * Endpoints which don't have a @group will be placed in this default group.
         */
        'default' => 'Endpoints',

        /*
         * By default, Scribe will sort groups alphabetically, and endpoints in the order their routes are defined.
         * You can override this by listing the groups, subgroups and endpoints here in the order you want them.
         *
         * Any groups, subgroups or endpoints you don't list here will be added as usual after the ones here.
         * If an endpoint/subgroup is listed under a group it doesn't belong in, it will be ignored.
         * Note: you must include the initial '/' when writing an endpoint.
         */
        'order' => [
            // 'This group will come first',
            // 'This group will come next' => [
            //     'POST /this-endpoint-will-comes-first',
            //     'GET /this-endpoint-will-comes-next',
            // ],
            // 'This group will come third' => [
            //     'This subgroup will come first' => [
            //         'GET /this-other-endpoint-will-comes-first',
            //         'GET /this-other-endpoint-will-comes-next',
            //     ]
            // ]
        ],
    ],

    /*
     * Custom logo path. This will be used as the value of the src attribute for the <img> tag,
     * so make sure it points to an accessible URL or path. Set to false to not use a logo.
     *
     * For example, if your logo is in public/img:
     * - 'logo' => '../img/logo.png' // for `static` type (output folder is public/docs)
     * - 'logo' => 'img/logo.png' // for `laravel` type
     *
     */
    'logo' => false,

    /**
     * Customize the "Last updated" value displayed in the docs by specifying tokens and formats.
     * Examples:
     * - {date:F j Y} => March 28, 2022
     * - {git:short} => Short hash of the last Git commit
     *
     * Available tokens are `{date:<format>}` and `{git:<format>}`.
     * The format you pass to `date` will be passed to PhP's `date()` function.
     * The format you pass to `git` can be either "short" or "long".
     */
    'last_updated' => 'Last updated: {date:F j, Y}',

    'examples' => [
        /*
         * If you would like the package to generate the same example values for parameters on each run,
         * set this to any number (eg. 1234)
         */
        'faker_seed' => null,

        /*
         * With API resources and transformers, Scribe tries to generate example models to use in your API responses.
         * By default, Scribe will try the model's factory, and if that fails, try fetching the first from the database.
         * You can reorder or remove strategies here.
         */
        'models_source' => ['factoryCreate', 'factoryMake', 'databaseFirst'],
    ],

    /**
     * The strategies Scribe will use to extract information about your routes at each stage.
     * If you create or install a custom strategy, add it here.
     */
    'strategies' => [
        'metadata' => [
            Strategies\Metadata\GetFromDocBlocks::class,
            Strategies\Metadata\GetFromMetadataAttributes::class,
        ],
        'urlParameters' => [
            Strategies\UrlParameters\GetFromLaravelAPI::class,
            Strategies\UrlParameters\GetFromLumenAPI::class,
            Strategies\UrlParameters\GetFromUrlParamAttribute::class,
            Strategies\UrlParameters\GetFromUrlParamTag::class,
        ],
        'queryParameters' => [
            Strategies\QueryParameters\GetFromFormRequest::class,
            Strategies\QueryParameters\GetFromInlineValidator::class,
            Strategies\QueryParameters\GetFromQueryParamAttribute::class,
            Strategies\QueryParameters\GetFromQueryParamTag::class,
        ],
        'headers' => [
            Strategies\Headers\GetFromRouteRules::class,
            Strategies\Headers\GetFromHeaderAttribute::class,
            Strategies\Headers\GetFromHeaderTag::class,
        ],
        'bodyParameters' => [
            Strategies\BodyParameters\GetFromFormRequest::class,
            Strategies\BodyParameters\GetFromInlineValidator::class,
            Strategies\BodyParameters\GetFromBodyParamAttribute::class,
            Strategies\BodyParameters\GetFromBodyParamTag::class,
        ],
        'responses' => [
            Strategies\Responses\UseResponseAttributes::class,
            Strategies\Responses\UseTransformerTags::class,
            Strategies\Responses\UseApiResourceTags::class,
            Strategies\Responses\UseResponseTag::class,
            Strategies\Responses\UseResponseFileTag::class,
            Strategies\Responses\ResponseCalls::class,
        ],
        'responseFields' => [
            Strategies\ResponseFields\GetFromResponseFieldAttribute::class,
            Strategies\ResponseFields\GetFromResponseFieldTag::class,
        ],
    ],

    'fractal' => [
        /* If you are using a custom serializer with league/fractal, you can specify it here.
         * Leave as null to use no serializer or return simple JSON.
         */
        'serializer' => null,
    ],

    /*
     * [Advanced] Custom implementation of RouteMatcherInterface to customise how routes are matched
     *
     */
    'routeMatcher' => \Knuckles\Scribe\Matching\RouteMatcher::class,

    /**
     * For response calls, API resource responses and transformer responses,
     * Scribe will try to start database transactions, so no changes are persisted to your database.
     * Tell Scribe which connections should be transacted here.
     * If you only use one db connection, you can leave this as is.
     */
    'database_connections_to_transact' => [config('database.default')]
];

Document your API

The next step is to document your API. Scribe provides two ways how you can document your API; Docblock and Attribute.

Dockblock is a formatted comment that is used to explain a specific segment of a source code.

Attributes on the other hand are classes that can be used to add metadata to other classes.

In this section, I will use Docblock to add documentation

/**
     * Login
     *
     * This endpoint is used to login a user to the system.
     *
     * @bodyParam email string required Example: [email protected]
     * @bodyParam password string required Example: 12345678
     *
     * @response scenario="Successful Login" {
     * "message": "User Login Successfully",
     * "access_token": "8|MgowQLkdpShwrb8AI9j1YAGmwnDjAOeE17XrP5nb",
     * "token_type": "Bearer"
     * }
     *
     * @response 401 scenario="Failed Login"{
     * "message": "Invalid login credentials"
     * }
     *
     */
    public function login(Request $request)
    {
      // Add some logic
    }

We can generate the documentation using the scribe:generate command

php artisan scribe:generate 

The resulting documentation is seen below

rest api documentation

Grouping Endpoints

By default, most APIs have a lot of resources. These resources can range from Products to Authentication to Orders.

It is important to have a clear structure in your documentation so that other developers working with your API can find the relevant resources easily.

Scribe allows us to group endpoints easily. With a single @group annotation, you can have all your endpoints for a particular resource grouped together.

/**
 * @group Products
 *
 * APIs for managing Products
 */
class ProductsController extends Controller
{
}

This results in structured Documentation as shown

rest api group endpoints
Grouping Endpoints

Authentication

One of the key features of any API is the ability to provide Authentication. It is important to provide a clear way for how other developers will authenticate themselves with your API. This can be through client ids and secrets or the default username and password.

Scribe discusses how you can configure Authentication in this part. This allows other developers to interact with your API through the documentation as if they are logged in and can then view the responses for various API Calls.

It also generates an Authentication guide making your life easier.

rest api authentication

Authenticated Endpoints

You might also want to indicate that certain endpoints need authentication in order to access them. Typically this would mean a client would need to provide a valid access token in order to access the resource.

Scribe also provides a cool way of indicating an endpoint is protected. Using the @authenticated annotation, you can have a simple “requires authentication” badge displayed on your documentation.

/**
 * @group Products
 *
 * APIs for managing Products
 *

 * @authenticated
 */
class ProductsController extends Controller
{
}

The badge is displayed as shown

rest api authenticated endpoints

Requesting Headers Metadata

Headers are an important factor in a REST API. They provide important meta-data that tells the API how to respond to your client.

Examples of these meta-data are Content-type, Authorization, and User-agent just to name a few.

For example, a client might want to specify that it is ok receiving JSON-formatted data. Therefore, by adding an Accept: application/json to its headers, the API can format and return the response in JSON format.

Another client might be using XML and as a result, might want to inform the API to return the response in XML format. The client would need to add the Accept: application/xml header so that the API responds with the correct format.

Similarly, an API might be supporting only JSON format and as a result, you might want to notify relevant clients that your API only supports JSON and thus any data passed to or requested from the API must be in JSON format.

Scribe allows us to specify the relevant headers required by our API

/**
 * @group Products
 *
 * APIs for managing Products
 *
 * @header Content-Type application/json
 * @authenticated
 */
class ProductsController extends Controller
{
}

This creates a new section in the documentation stating the relevant headers.

rest api headers

Requesting Query, Url and Body Parameters

The main part of an API is specifying the relevant parameters that can be passed to the API and receive a relevant response.

Parameters can be passed in three main ways; in the body, in the URL or as a query parameter.

Body Parameters

These are variables that are passed to an API mainly through a POST or PUT/PATCH request.

In our case, to add a new product to the database, we make a post request to the /api/v1/products endpoint and pass some relevant data along so that the record is created.

We can specify these parameters using the @bodyParam annotation. We can also specify if the parameters are required.

//App/Http/Controllers/ProductsController

use App\Http\Resources\ProductResource;
use App\Models\Products;
use Illuminate\Http\Request;

/**
     * Add Products to the Database
     *
     * This endpoint is used to add a product to the database.
     *
     * @bodyParam name string required Example: Laptop
     * @bodyParam price double required Example: 199
     * @bodyParam description string required
     *
     *@response 201 scenario="Add a Product"{
     * "data": {
     *   "id": 2,
     *   "product_name": "veritatis",
     *   "product_price": "$30",
     *   "discounted_price": "$27",
     *   "discount": "$3",
     *   "product_description": "Esse cupiditate eaque qui laboriosam quis id."
     * }
     *}
     */
    public function store(Request $request)
    {
        $product_name = $request->input('name');
        $product_price = $request->input('price');
        $product_description = $request->input('description');

        $product = Products::create([
            'name' => $product_name,
            'price' => $product_price,
            'description' => $product_description,
        ]);
        return response()->json([
            'data' => new ProductResource($product)
        ], 201);
    }

Scribe produces the documentation for the Resource as shown

rest api body parameters

URL Parameters

Sometimes you might want to request a URL parameter to return a more refined response. We usually pass the resource id and the result is a response with a single record.

In my case, I might want to return a single product and thus I can make a GET request to the api/v1/products/1 endpoint and this returns a single record.

Using the @urlParam annotation, you can specify which parameters are required.

//App/Http/Controllers/ProductsController

use App\Http\Resources\ProductResource;
use App\Models\Products;

/**
     * Get a Single Product
     *
     * This endpoint is used to return a single products from the database.
     *
     * @urlParam id integer required The ID of the product.
     *
     * @response scenario="Get a Single Product"{
     * "data": {
     *   "id": 2,
     *   "product_name": "veritatis",
     *   "product_price": "$30",
     *   "discounted_price": "$27",
     *   "discount": "$3",
     *   "product_description": "Esse cupiditate eaque qui laboriosam quis id."
     * }
     *}
     */
    public function show(Products $product)
    {
        return new ProductResource($product);
    }

This will then be included in your API documentation.

rest api url parameters

Query Parameters

Query parameters can be used to further customize the response returned by an API.

For example, if your API is paginated, you can have the page returned as a query parameter in order to return the response.i.e /api/v1/products?page=4

Scribe provides the @queryParam annotation that allows us to specify query parameters that can be used to customize the response of the API.

//App/Http/Controllers/ProductsController

use App\Http\Resources\ProductResource;
use App\Models\Products;

/**
     * Get All Products
     *
     * This endpoint is used to fetch all products available in the database.
     *
     * @queryParam page int The page number from pagination. Defaut is '1' Example: 1
     *
     * @response scenario="Get All Products"{
     *"data": [
     *    {
     *    "id": 1,
     *        "product_name": "quo",
     *        "product_price": "$15",
     *        "discounted_price": "$13.5",
     *        "discount": "$1.5",
     *        "product_description": "Ut rerum aut deleniti eveniet ad et ullam perferendis."
     *    },
     *    {
     *        "id": 2,
     *        "product_name": "Laptop",
     *        "product_price": "$500",
     *        "discounted_price": "$450",
     *        "discount": "$50",
     *        "product_description": "This is a brand new laptop"
     *    }
     *  ]
     *}
     */
    public function index()
    {
        return ProductResource::collection(Products::paginate(5));
    }

This results in another section containing the query parameters

rest api query parameters

Documenting Responses

The last section to add to your documentation is the responses. It is important to return a sample response for your API calls so that others can know what to expect when they interact with your API.

You can add a successful response and a failed response with the relevant error messages and status codes so that another developer is able to use the API.

Another annotation provided to us by scribe is @response. You can add a sample response and its status code to your documentation.

//App/Http/Controllers/ProductsController

use App\Http\Resources\ProductResource;
use App\Models\Products;

/**
     * Get a Single Product
     *
     * This endpoint is used to return a single products from the database.
     *
     * @urlParam id integer required The ID of the product.
     *
     * @response scenario="Get a Single Product"{
     * "data": {
     *   "id": 2,
     *   "product_name": "veritatis",
     *   "product_price": "$30",
     *   "discounted_price": "$27",
     *   "discount": "$3",
     *   "product_description": "Esse cupiditate eaque qui laboriosam quis id."
     * }
     *}
     */
    public function show(Products $product)
    {
        return new ProductResource($product);
    }

This will display a successful response and a failed response on your documentation

api response

Scribe provides a lot more features for documenting your responses. You can read it here.

You should run the scribe:generate command each time you want to update your documentation.

Once you have finished your documentation, you can run the command php artisan scribe:generate and your new documentation is now ready.

Head over to yourdomain.com/docs to view your generated documentation.

Documentation

Key Takeaways

Documenting your API is an essential part of developing your API. It not only makes the life of the ones using it easy but also allows you to explain complex functionalities of your API in a simple and understandable format.

To summarize, your API documentation should follow these 3 C’s;

  • Clear – One should be able to understand from a bird’s eye view what your API does
  • Concise – One should be able to have all their questions about your API answered by the documentation
  • Complete – One should be able to interact with the API without any help simply by reading the Documentation

In Closing

Documenting your API is a must if you want other developers to use your API. Your API documentation can also be used as a Content Marketing Machine as it can bring SEO traffic to your business from people searching for solutions to their problems.

You can find the sample documentation generated in this article here.

I hope this article helped you document your REST API. What do you think I left out? Thank you for reading.

You can watch this video to learn how to use your Technical Documentation as a Content Marketing Tool

- Scribe Documentation: https://scribe.knuckles.wtf/laravel/
- https://memorandum.ewilan-riviere.com/development/frameworks/laravel/setup-dependencies/
- https://gitlab.com/cpdrenato/lara6-doc

- https://www.iankumu.com/blog/laravel-rest-api-documentation/

12

Share

Donate to Site


About Author

Renato

Developer

Add a Comment
Comments 0 Comments

No comments yet! Be the first to comment

Blog Search


Categories

OUTROS (16) Variados (109) PHP (133) Laravel (171) Black Hat (3) front-end (29) linux (114) postgresql (39) Docker (28) rest (5) soap (1) webservice (6) October (1) CMS (2) node (7) backend (13) ubuntu (56) devops (25) nodejs (5) npm (3) nvm (1) git (8) firefox (1) react (7) reactnative (5) collections (1) javascript (7) reactjs (8) yarn (0) adb (1) Solid (2) blade (3) models (1) controllers (0) log (1) html (2) hardware (3) aws (14) Transcribe (2) transcription (1) google (4) ibm (1) nuance (1) PHP Swoole (5) mysql (31) macox (4) flutter (1) symfony (1) cor (1) colors (2) homeOffice (2) jobs (3) imagick (2) ec2 (1) sw (1) websocket (2) markdown (1) ckeditor (1) tecnologia (14) faceapp (1) eloquent (14) query (4) sql (40) ddd (3) nginx (9) apache (4) certbot (1) lets-encrypt (3) debian (12) liquid (1) magento (2) ruby (1) LETSENCRYPT (1) Fibonacci (1) wine (1) transaction (1) pendrive (1) boot (1) usb (1) prf (1) policia (2) federal (1) lucena (1) mongodb (4) paypal (1) payment (1) zend (1) vim (4) ciencia (6) js (1) nosql (1) java (1) JasperReports (1) phpjasper (1) covid19 (1) saude (1) athena (1) cinnamon (1) phpunit (2) binaural (1) mysqli (3) database (42) windows (6) vala (1) json (2) oracle (1) mariadb (4) dev (12) webdev (24) s3 (4) storage (1) kitematic (1) gnome (2) web (2) intel (3) piada (1) cron (2) dba (18) lumen (1) ffmpeg (2) android (2) aplicativo (1) fedora (2) shell (4) bash (3) script (3) lider (1) htm (1) csv (1) dropbox (1) db (3) combustivel (2) haru (1) presenter (1) gasolina (1) MeioAmbiente (1) Grunt (1) biologia (1) programming (22) performance (3) brain (1) smartphones (1) telefonia (1) privacidade (1) opensource (3) microg (1) iode (1) ssh (3) zsh (2) terminal (3) dracula (1) spaceship (1) mac (2) idiomas (1) laptop (2) developer (37) api (5) data (1) matematica (1) seguranca (2) 100DaysOfCode (9) hotfix (1) documentation (1) laravelphp (10) RabbitMQ (3) Elasticsearch (1) redis (2) Raspberry (4) Padrao de design (4) JQuery (1) angularjs (4) Dicas (43) Kubernetes (3) vscode (2) backup (1) angular (3) servers (2) pipelines (1) AppSec (1) DevSecOps (4) rust (1) RustLang (1) Mozilla (1) algoritimo (1) sqlite (1) Passport (2) jwt (5) security (2) translate (1) kube (2) iot (1) politica (2) bolsonaro (1) flow (1) podcast (1) Brasil (1) containers (3) traefik (1) networking (1) host (1) POO (2) microservices (2) bug (1) cqrs (1) arquitetura (3) Architecture (4) sail (3) militar (1) artigo (1) economia (1) forcas armadas (1) ffaa (1) autenticacao (2) autorizacao (2) authentication (4) authorization (3) NoCookies (1) wsl (4) memcached (1) macos (2) unix (2) kali-linux (1) linux-tools (5) apple (1) noticias (2) composer (1) rancher (1) k8s (1) escopos (1) orm (1) jenkins (4) github (5) gitlab (3) queue (1) Passwordless (1) sonarqube (1) phpswoole (1) laraveloctane (1) Swoole (1) Swoole (1) octane (1) Structurizr (1) Diagramas (1) c4 (1) c4-models (1) compactar (1) compression (1) messaging (1) restfull (1) eventdrive (1) services (1) http (1) Monolith (1) microservice (1) historia (1) educacao (1) cavalotroia (1) OOD (0) odd (1) chatgpt (1) openai (3) vicuna (1) llama (1) gpt (1) transformers (1) pytorch (1) tensorflow (1) akitando (1) ia (1) nvidia (1) agi (1) guard (1) multiple_authen (2) rpi (1) auth (1) auth (1) livros (2) ElonMusk (2) Oh My Zsh (1) Manjaro (1) BigLinux (2) ArchLinux (1) Migration (1) Error (1) Monitor (1) Filament (1) LaravelFilament (1) replication (1) phpfpm (1) cache (1) vpn (1) l2tp (1) zorin-os (1) optimization (1) scheduling (1) monitoring (2) linkedin (1) community (1) inteligencia-artificial (2) wsl2 (1) maps (1) API_KEY_GOOGLE_MAPS (1) repmgr (1) altadisponibilidade (1) banco (1) modelagemdedados (1) inteligenciadedados (4) governancadedados (1) bancodedados (2) Observability (1) picpay (1) ecommerce (1) Curisidades (1) Samurai (1) KubeCon (1) GitOps (1) Axios (1) Fetch (1) Deepin (1) vue (4) nuxt (1) PKCE (1) Oauth2 (2) webhook (1) TypeScript (1) tailwind (1) gource (2)

New Articles



Get Latest Updates by Email