### Specify or Omit Examples for Parameters Source: https://scribe.knuckles.wtf/laravel/documenting/query-body-parameters Control example generation by appending `Example: ` to descriptions for tags or using the `example:` argument for attributes. Use `No-example` to omit optional parameters from examples. ```php /** * @queryParam sort Field to sort by. Defaults to 'id'. Example: published_at * @queryParam fields required Comma-separated fields to include in the response. Example: title,published_at,id * @queryParam filters[published_at] Filter by date published. No-example */ #[QueryParam("filters[title]", "Filter by title.", required: false, example: "No-example")] public function endpoint() ``` -------------------------------- ### Publish Scribe Example Request Templates Source: https://scribe.knuckles.wtf/laravel/advanced/theming Use this command to publish only the example request templates. This is useful if you only want to customize how example requests are displayed. ```bash php artisan vendor:publish --tag=scribe-examples ``` -------------------------------- ### Strategy Settings Example Source: https://scribe.knuckles.wtf/laravel/advanced/plugins An example of the settings array passed to a strategy when configured with `wrapWithSettings`. The strategy can then use these settings to adjust its behavior. ```php [ 'paginationType' => 'cursor' ], ``` -------------------------------- ### Bootstrap Hook Example Source: https://scribe.knuckles.wtf/laravel/hooks Use the `bootstrap()` hook to run code when the Scribe generate command starts. The callback receives the `GenerateDocumentation` command instance. Always wrap hook calls in `if (class_exists(\Knuckles\Scribe\Scribe::class))` for safe production deployment. ```php use Knuckles\Scribe\Commands\GenerateDocumentation; use Knuckles\Scribe\Scribe; use Event; public function boot() { if (class_exists(\Knuckles\Scribe\Scribe::class)) { Scribe::bootstrap(function (GenerateDocumentation $command) { Event::fake(); }); } } ``` -------------------------------- ### Install Laravel Dependencies Source: https://scribe.knuckles.wtf/laravel/contributing Install the regular Laravel dependencies required for the project. ```bash composer install ``` -------------------------------- ### Ruby Example Request Template Source: https://scribe.knuckles.wtf/laravel/advanced/example-requests This Blade template generates a Ruby example request using the rest-client library. It dynamically includes body parameters, headers, and constructs the request based on endpoint data. Ensure rest-client is installed in your Ruby environment. ```blade @php // Adding this so we get IDE code completion for $endpoint /** @var \Knuckles\Camel\Output\OutputEndpointData $endpoint */ @endphp ```ruby require 'rest-client' @if(!empty($endpoint->cleanBodyParameters)) body = {!! json_encode($endpoint->cleanBodyParameters, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE) !!} @endif @if(!empty($endpoint->headers)) headers = { @foreach($endpoint->headers as $header => $value) "{{$header}}": "{{$value}}", @endforeach } @endif response = RestClient.{{strtolower($endpoint->httpMethods[0])}}( '{{ $baseUrl }}/{{ $endpoint->boundUri }}'@if(!empty($endpoint->cleanBodyParameters)), body @endif @if(!empty($endpoint->headers)), headers @endif ) p response.body ``` ``` -------------------------------- ### Implement Strategy Logic for Pagination Source: https://scribe.knuckles.wtf/laravel/advanced/plugins This strategy logic checks if the endpoint is a GET request for an index route and returns parameter information for 'page' and 'pageSize'. The 'pageSize' is marked as not required and without an example to omit it from example requests. ```php public function __invoke(ExtractedEndpointData $endpointData, array $settings = []): ?array { $isGetRoute = in_array('GET', $endpointData->httpMethods); $isIndexRoute = strpos($endpointData->route->getName(), '.index') !== false; if ($isGetRoute && $isIndexRoute) { return [ 'page' => [ 'description' => 'Page number to return.', 'required' => false, 'example' => 1, ], 'pageSize' => [ 'description' => 'Number of items to return in a page. Defaults to 10.', 'required' => false, 'example' => null, // We don't want it to show in examples ], ]; } return null; } ``` -------------------------------- ### Get Routes for Documentation Source: https://scribe.knuckles.wtf/laravel/architecture This command fetches all application routes and filters them based on configuration for documentation generation. ```php $routes = $routeMatcher->getRoutes($yourConfig); ``` -------------------------------- ### Example Route Matching Source: https://scribe.knuckles.wtf/laravel/reference/config Illustrates which routes will be matched by Scribe based on the 'api/*' prefix configuration. ```php // 👍 Will match Route::get('/api/users', [UserController::class, 'listUsers']); Route::post('/api/users', [UserController::class, 'createUser']); // ❌ Won't match Route::get('/status', [StatusController::class, 'getStatus']); ``` -------------------------------- ### Specifying and Omitting Examples Source: https://scribe.knuckles.wtf/laravel/documenting/query-body-parameters Control example generation for parameters by providing specific values or using 'No-example'. ```APIDOC ## GET /api/endpoint ### Description An example endpoint demonstrating custom parameter examples. ### Method GET ### Endpoint /api/endpoint ### Parameters #### Query Parameters - **sort** (string) - Optional - Field to sort by. Defaults to 'id'. Example: published_at - **fields** (string) - Required - Comma-separated fields to include in the response. Example: title,published_at,id - **filters[published_at]** (string) - Optional - Filter by date published. ### Request Example ```json { "sort": "published_at", "fields": "title,published_at,id" } ``` ``` -------------------------------- ### Returning URL/Query/Body Parameters from Strategy Source: https://scribe.knuckles.wtf/laravel/reference/plugin-api Illustrates how to define URL, query, or body parameters for an endpoint. Each parameter can have a type, description, example, and a required flag. ```php return [ 'room_id' => [ 'type' => 'string', 'description' => '', 'example' => 'r4oiu78t63ns3', 'required' => true, ] ]; ``` -------------------------------- ### Describe Example Responses with @response Source: https://scribe.knuckles.wtf/laravel/reference/annotations Use the @response annotation to describe example responses. You can specify the HTTP status code and a JSON object or string. If no status is provided, it defaults to 200. You can also add a scenario description. ```php @response {"a": "b"} @response 201 {"a": "b"} @response 201 {"a": "b"} scenario="Operation successful" @response status=201 scenario="Operation successful" {"a": "b"} @response scenario=Success {"a": "b"} @response 201 scenario="Operation successful" {"a": "b"} ``` -------------------------------- ### Subdomain Route Matching Example Source: https://scribe.knuckles.wtf/laravel/reference/config Demonstrates how to match routes within a specific domain, such as 'v2.acme.co', using route group configurations. ```php // 👍 Will match Route::group(['domain' => 'v2.acme.co'], function () { Route::get('/api/users', [UserController::class, 'listUsers']); Route::post('/api/users', [UserController::class, 'createUser']); }); // ❌ Won't match Route::get('/api/getUsers', [UserControllerV::class, 'listUsers']); ``` -------------------------------- ### Example Scribe Query Parameter Annotations Source: https://scribe.knuckles.wtf/laravel/documenting/query-body-parameters This example shows how to document query parameters, including sorting, field selection, and filtering with nested objects. ```php /** * @queryParam sort string Field to sort by. Defaults to 'id'. * @queryParam fields string[] required Comma-separated list of fields to include in the response. Example: title,published_at,is_public * @queryParam filters object Fields to filter by * @queryParam filters.published_at Filter by date published. * @queryParam filters.is_public integer Filter by whether a post is public or not. Example: 1 */ ``` -------------------------------- ### Specify Example Request Languages Source: https://scribe.knuckles.wtf/laravel/reference/config Choose the languages for which example requests will be generated. Default includes bash, javascript, php, and python. Custom languages require corresponding Blade views. ```php 'example_languages' => ['bash', 'javascript'] ``` -------------------------------- ### Define Query Parameters with Docblocks Source: https://scribe.knuckles.wtf/laravel/reference/annotations Use docblock annotations to describe query parameters. Specify type, requirement, allowed values (Enum), and examples. Use 'No-example' to exclude from generated examples. ```php @queryParam date The date. Example: 2022-01-01 @queryParam language The language. Enum: en, de, fr @queryParam language The language. Enum: en, de, fr. Example: en @queryParam page int @queryParam page int The page number. @queryParam page int required The page number. Example: 4 @queryParam page int The page number. No-example ``` -------------------------------- ### Set Faker Seed for Example Generation Source: https://scribe.knuckles.wtf/laravel/reference/config Set a numeric seed to generate consistent example values using fakerphp/faker. ```php faker_seed: 1234 ``` -------------------------------- ### Using #[Response] Attribute for Example Responses Source: https://scribe.knuckles.wtf/laravel/documenting/responses This snippet shows how to use the #[Response] attribute in PHP to provide JSON or array examples for an endpoint. ```APIDOC ## GET /api/users/{id} ### Description This endpoint demonstrates using the #[Response] attribute to provide example responses, either as a JSON string or a PHP array. ### Method GET ### Endpoint /api/users/{id} ### Parameters #### Path Parameters - **id** (integer) - Required - The ID of the user to retrieve. ### Response #### Success Response (200) - **id** (integer) - The ID of the user. - **name** (string) - The name of the user. - **roles** (array) - The roles assigned to the user. ### Response Example ```json { "id": 4, "name": "Jessica Jones", "roles": ["admin"] } ``` ``` -------------------------------- ### Omitting Parameters from Examples Source: https://scribe.knuckles.wtf/laravel/documenting/url-parameters Demonstrates how to prevent a parameter from being included in generated examples using 'No-example'. ```APIDOC ## GET /post/{id}/{lang?} ### Description Retrieves a post by its ID and optionally filters by language. The 'lang' parameter will be omitted from examples. ### Method GET ### Endpoint /post/{id}/{lang?} ### Parameters #### Path Parameters - **id** (string) - Required - The ID of the post. - **lang** (string) - Optional - The language. No-example ### Request Example ```json { "example": "Not applicable for GET request" } ``` ### Response #### Success Response (200) - **field1** (type) - Description #### Response Example ```json { "example": "response body" } ``` ``` -------------------------------- ### Configure Example Languages in Scribe Source: https://scribe.knuckles.wtf/laravel/advanced/example-requests Add new languages for example requests to the `example_languages` array in your `config/scribe.php` file. You can use a simple string for the language name or an associative array to specify a custom display name. ```php 'example_languages' => [ 'javascript', 'ruby', // or 'Ruby 3' => 'ruby', ] ``` -------------------------------- ### Base CRUD Controller Example Source: https://scribe.knuckles.wtf/laravel/tasks/sorting-and-inheritance This is a base controller with a `resource` property and an `index` method. It demonstrates a common pattern for handling resource-based operations. ```php class CRUDController { public string $resource; public function index() { $class = $this->resource; return $class::paginate(20); } public function create() { // ... } // ... } ``` -------------------------------- ### Example Scribe Body Parameter Annotations Source: https://scribe.knuckles.wtf/laravel/documenting/query-body-parameters This example demonstrates a combination of nested objects, arrays of objects, and primitive arrays for body parameters. ```php /** * @bodyParam user object required The user details * @bodyParam user.name string required The user's name * @bodyParam user.age string required The user's age * @bodyParam friend_ids int[] List of the user's friends. * @bodyParam cars object[] List of cars * @bodyParam cars[].year string The year the car was made. Example: 1997 * @bodyParam cars[].make string The make of the car. Example: Toyota */ ``` -------------------------------- ### Full Scribe Authentication Configuration Example Source: https://scribe.knuckles.wtf/laravel/documenting/api-information Comprehensive configuration for API authentication in Scribe, including default behavior, token value, placeholder, and extra information. ```php return [ // ... 'auth' => [ 'enabled' => true, 'default' => false, 'in' => 'bearer', 'name' => 'Authorization', 'use_value' => env('SCRIBE_AUTH_KEY'), 'placeholder' => '{ACCESS_TOKEN}', 'extra_info' => 'You can retrieve your token by visiting your dashboard and clicking Generate API token.', ], ]; ``` -------------------------------- ### Using @response Tag for Example Responses Source: https://scribe.knuckles.wtf/laravel/documenting/responses This snippet demonstrates how to use the @response tag in a Docblock to provide a JSON example response for an endpoint. ```APIDOC ## POST /api/users ### Description This endpoint shows how to define an example response using the @response tag. ### Method POST ### Endpoint /api/users ### Request Body - **name** (string) - Required - The name of the user. - **email** (string) - Required - The email of the user. ### Request Example ```json { "name": "John Doe", "email": "john.doe@example.com" } ``` ### Response #### Success Response (200) - **id** (integer) - The ID of the created user. - **name** (string) - The name of the created user. - **roles** (array) - The roles assigned to the user. ### Response Example ```json { "id": 4, "name": "Jessica Jones", "roles": ["admin"] } ``` ``` -------------------------------- ### Custom OpenAPI Generator for Components Source: https://scribe.knuckles.wtf/laravel/migrating Example of creating a custom OpenAPI generator class that extends `OpenApiGenerator`. This specific example demonstrates how to add a parameter to the `components` section of the OpenAPI specification. ```php class ComponentsOpenApiGenerator extends OpenApiGenerator { public function root(array $root, array $groupedEndpoints): array { $parameters = Arr::get($root, 'components.parameters', []); $parameters = array_merge($parameters, [ 'slugParam' => [ 'in' => 'path', 'name' => 'slug', 'description' => 'The slug of the organization.', 'example' => 'acme-corp', 'required' => true, 'schema' => [ 'type' => 'string', ], ], ]); $root['components']['parameters'] = $parameters; return $root; } public function pathParameters(array $parameters, array $endpoints, array $urlParameters): array { $parameters['slug'] = ['$ref' => "#/components/parameters/slugParam"]; return $parameters; } } ``` -------------------------------- ### Describe Response from File with @responseFile Source: https://scribe.knuckles.wtf/laravel/reference/annotations Use the @responseFile annotation to specify a file containing an example response. The path can be absolute, relative to the project root, or relative to the Laravel storage directory. Defaults to status 200. ```php @responseFile /an/absolute/path @responseFile 400 relative/path/from/your/project/root @responseFile status=400 scenario="Failed" path/from/your/laravel/storage/directory @responseFile 400 scenario="Failed" path/from/your/laravel/storage/directory ``` -------------------------------- ### Omit Optional Parameter from Examples Source: https://scribe.knuckles.wtf/laravel/documenting/url-parameters To prevent an optional parameter from being included in generated examples and response calls, append 'No-example' to its description in the @urlParam tag. ```php /** * @urlParam id required The ID of the post. * @urlParam lang The language. No-example */ ``` -------------------------------- ### Provide JSON Response with Attributes Source: https://scribe.knuckles.wtf/laravel/documenting/responses Use the `#[Response]` attribute with a JSON string or a PHP array to define an example response. This is an alternative to docblock tags. ```php use Knuckles\Scribe\Attributes\Response; // As a string #[Response(<< 4, "name" => "Jessica Jones", "roles" => ["admin"], ])] public function show($id) { return User::findOrFail($id); } ``` -------------------------------- ### Configure Model Source Strategies Source: https://scribe.knuckles.wtf/laravel/reference/config Define the order of strategies Scribe uses to generate example models for API responses. Options include 'factoryCreate', 'factoryMake', and 'databaseFirst'. ```php 'models_source' => ['factoryCreate', 'factoryMake', 'databaseFirst'] ``` -------------------------------- ### Describe Example Responses with #[Response] Attribute Source: https://scribe.knuckles.wtf/laravel/reference/annotations Use the #[Response] attribute for defining example responses in PHP 8+ code. It supports JSON strings or arrays for the response body, an optional status code, and an optional scenario description. ```php #[Response('{"a": "b"}')] #[Response(["a" => "b"])] #[Response(["a" => "b"], 201)] #[Response('{"a": "b"}', 201, "Operation successful")] #[Response(["a" => "b"], description: "Success")] public function endpoint() {...} ``` -------------------------------- ### Example of Paths Array in afterGenerating Source: https://scribe.knuckles.wtf/laravel/hooks This array structure illustrates the paths provided to the `afterGenerating` callback, including file paths for Postman and OpenAPI, and directory paths for assets. ```json [\n "postman" => "C:\\Users\\shalvah\\Projects\\TheSideProjectAPI\\punlic\\docs\\collection.json"\n "openapi" => "C:\\Users\\shalvah\\Projects\\TheSideProjectAPI\\punlic\\docs\\openapi.yaml"\n "html" => "C:\\Users\\shalvah\\Projects\\TheSideProjectAPI\\docs\\index.html"\n "blade" => null\n "assets" => [\n "js" => "C:\\Users\\shalvah\\Projects\\TheSideProjectAPI\\docs\\css"\n "css" => "C:\\Users\\shalvah\\Projects\\TheSideProjectAPI\\docs\\js"\n "images" => "C:\\Users\\shalvah\\Projects\\TheSideProjectAPI\\docs\\images"\n ]\n] ``` -------------------------------- ### Define Body Parameters with Docblocks Source: https://scribe.knuckles.wtf/laravel/reference/annotations Use docblock annotations to describe request body parameters. Specify type, requirement, allowed values (Enum), and examples. Nested objects and arrays are supported. Use 'No-example' to exclude from generated examples. ```php @bodyParam language string The language. Enum: en, de, fr @bodyParam language string The language. Enum: en, de, fr. Example: en @bodyParam room_id string @bodyParam room_id string required The room ID. @bodyParam room_id string The room ID. Example: r98639bgh3 @bodyParam room_id string Example: r98639bgh3 // Objects and arrays @bodyParam user object required The user data @bodyParam user.name string required The user's name. @bodyParam user.age int Example: 1000 @bodyParam people object[] required List of people @bodyParam people[].name string Example: Deadpool // If your entire request body is an array @bodyParam [] object[] required List of things to do @bodyParam [].name string Name of the thing. Example: Cook ``` -------------------------------- ### Laravel Route Definition Source: https://scribe.knuckles.wtf/laravel/documenting/url-parameters Example of a Laravel route definition with optional parameters. ```php Route::get("/post/{id}/{lang?}"); ``` -------------------------------- ### Example Merged Response Source: https://scribe.knuckles.wtf/laravel/documenting/responses Illustrates the final merged JSON response when using inline data with a response file. ```json { "type": "User", "result": "not found" } ``` -------------------------------- ### Specify Response Status Code with Attributes Source: https://scribe.knuckles.wtf/laravel/documenting/responses Use the `#[Response]` attribute to specify a status code for the example response. The status code is passed as the second argument. ```php #[Response('{"id": 4, "name": "Jessica Jones"}', 201)] ``` -------------------------------- ### Run Tests with Filter Source: https://scribe.knuckles.wtf/laravel/contributing Pass options to PHPUnit to filter tests, for example, by using `--filter` to specify a test case. ```bash composer test -- --filter can_fetch_from_responsefile_tag ``` -------------------------------- ### Returning Metadata from Strategy Source: https://scribe.knuckles.wtf/laravel/reference/plugin-api Example of returning metadata attributes from the `__invoke` method. This includes group information, endpoint title, description, and authentication status. ```php return [ 'groupName' => 'User management', 'groupDescription' => 'APIs to manage users.', 'title' => 'Shadowban a user', 'description' => "Temporarily restrict a user's account", 'authenticated' => true, 'custom' => [], ]; ``` -------------------------------- ### Describe Response from File with #[ResponseFile] Attribute Source: https://scribe.knuckles.wtf/laravel/reference/annotations Use the #[ResponseFile] attribute to reference a file for example responses. Supports absolute or relative paths and an optional HTTP status code and scenario description. ```php #[ResponseFile("/an/absolute/path")] #[ResponseFile("relative/path/from/your/project/root", 400)] #[ResponseFile("path/from/your/laravel/storage/directory", 400, description: "Failed")] public function endpoint() {...} ``` -------------------------------- ### Describe URL Parameter with Docblock Tags Source: https://scribe.knuckles.wtf/laravel/reference/annotations Use the @urlParam tag to describe URL parameters. You can specify the name, type, requirement, description, enum values, and an example. ```php @urlParam id ``` ```php @urlParam id int ``` ```php @urlParam id int required ``` ```php @urlParam id int required The user's ID. ``` ```php @urlParam language The language. Enum: en, de, fr ``` ```php @urlParam language The language. Enum: en, de, fr. Example: en ``` ```php @urlParam id int required The user's ID. Example: 88683 ``` ```php @urlParam id int The user's ID. Example: 88683 ``` ```php @urlParam id int The user's ID. No-example ``` -------------------------------- ### Basic API Endpoint Definition Source: https://scribe.knuckles.wtf/laravel/documenting Defines a simple GET endpoint for health checking. Scribe can extract basic information like URL and example requests/responses from this. ```php Route::get('/healthcheck', function () { return [ 'status' => 'up', 'services' => [ 'database' => 'up', 'redis' => 'up', ], ]; }); ``` -------------------------------- ### Custom Routes for Multiple Docs Sets Source: https://scribe.knuckles.wtf/laravel/tasks/generating When generating multiple documentation sets with Scribe, you need to define custom routes in `routes/web.php` to access each set. This example shows how to set up routes for both default and admin documentation. ```php Route::view('/docs', 'scribe.index')->name('scribe'); Route::view('/admin/docs', 'scribe_admin.index')->name('scribe-admin'); ``` -------------------------------- ### Describe Query and Body Parameters with Attributes Source: https://scribe.knuckles.wtf/laravel/documenting/query-body-parameters Utilize PHP attributes like `#[QueryParam]` and `#[BodyParam]` for defining parameter details. This approach offers a more structured way to declare parameter types, requirements, and examples. ```php use Knuckles\Scribe\Attributes\BodyParam; use Knuckles\Scribe\Attributes\QueryParam; #[BodyParam("user_id", "int", "The id of the user.", example: 9)] #[BodyParam("room_id", "string", "The id of the room.", required: false)] #[BodyParam("forever", "boolean", "Whether to ban the user forever.", required: false, example: false)] #[BodyParam("another_one", "number", "This won't be added to the examples.", required: false, example: "No-example")] public function updateDetails() { } #[QueryParam("sort", "string", "Field to sort by. Defaults to 'id'.", required: false)] #[QueryParam("fields", "Comma-separated list of fields to include in the response.", example: "title,published_at,is_public")] #[QueryParam("filters[published_at]", "Filter by date published.", required: false)] #[QueryParam("filters[is_is_public]", "integer", "Filter by whether a post is public or not.", example: 1, required: false)] public function listPosts() { // ... } ``` -------------------------------- ### Returning Responses from Strategy Source: https://scribe.knuckles.wtf/laravel/reference/plugin-api Demonstrates how to define one or more responses for an endpoint, including status code, headers, description, and content. ```php return [ [ 'status' => 201, 'headers' => ['sample-header' => 'sample-value'], 'description' => 'Operation successful.', 'content' => '{"room": {"id": "r4oiu78t63ns3"}}', ], ]; ``` -------------------------------- ### Returning Headers from Strategy Source: https://scribe.knuckles.wtf/laravel/reference/plugin-api Shows how to return a map of headers and their values from the `__invoke` method for a specific endpoint. ```php return [ 'Api-Version' => null, 'Content-Type' => 'application/xml', ]; ``` -------------------------------- ### Generate Docs with a Specific Environment File Source: https://scribe.knuckles.wtf/laravel/tasks/generating Use the `--env` option to specify a custom environment file (e.g., `.env.docs`) for generating documentation. This allows for customized app behavior during documentation generation, such as disabling notifications. ```bash php artisan scribe:generate --env docs ``` -------------------------------- ### Set API Description and Intro Text Source: https://scribe.knuckles.wtf/laravel/documenting/api-information Define the API's description and introductory text using 'description' and 'intro_text' keys in scribe.php. Markdown and HTML are supported. The intro text appears after the description in the docs. ```php 'description' => 'Start (and never finish) side projects with this API.', 'intro_text' => << 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). INTRO ``` -------------------------------- ### Configure Strategy with Settings Source: https://scribe.knuckles.wtf/laravel/advanced/plugins Configure a custom strategy with specific settings using the `wrapWithSettings` method. This allows for conditional application and custom behavior based on provided settings. ```php 'strategies' => [ 'queryParameters' => [ \Strategies\QueryParameters\GetFromQueryParamTag::class, \App\Docs\Strategies\AddPaginationParameters::wrapWithSettings( only: ['GET *'], except: ['GET /me'], otherSettings: ['paginationType' => 'cursor'], ), ], ], ``` -------------------------------- ### Using New Scribe Config Helpers Source: https://scribe.knuckles.wtf/laravel/migrating Demonstrates the usage of new Scribe configuration constants and helper functions to manage strategies for metadata, headers, URL parameters, query parameters, body parameters, responses, and response fields. This approach streamlines configuration and makes it easier to follow package updates. ```php use Knuckles\Scribe\Config\Defaults; use function Knuckles\Scribe\Config\{removeStrategies, configureStrategy}; 'strategies' => [ 'metadata' => [ // I want to use the defaults ...Defaults::METADATA_STRATEGIES, ], 'headers' => [ // I want the defaults, except for some. ...removeStrategies( Defaults::HEADERS_STRATEGIES, [Strategies\Headers\GetFromHeaderTag::class] ) ], 'urlParameters' => [ // I want the defaults, plus my own strategy. ...Defaults::URL_PARAMETERS_STRATEGIES, App\Docs\Strategies\SomeCoolStuff::class, ], 'queryParameters' => [ // I want the defaults, plus my own strategy, but only on some endpoints ...Defaults::QUERY_PARAMETERS_STRATEGIES, // `wrapWithSettings` works on any strategy, inbuilt or custom App\Docs\Strategies\SomeCoolStuff::wrapWithSettings( only: ['POST /cool/*'], ), ], 'bodyParameters' => [ ...Defaults::BODY_PARAMETERS_STRATEGIES, // I want the defaults, plus my own strategy, but excluding some endpoints App\Docs\Strategies\SomeCoolStuff::wrapWithSettings( except: ['POST /uncool'], ), ], // I want the defaults, but I need to adjust the settings on one of them 'responses' => configureStrategy( Defaults::RESPONSES_STRATEGIES, Strategies\Responses\ResponseCalls::withSettings( only: ['GET *'], config: [ 'app.debug' => false, ] ) ), 'responseFields' => [ ...Defaults::RESPONSE_FIELDS_STRATEGIES, ], ] ``` -------------------------------- ### Response Annotations Source: https://scribe.knuckles.wtf/laravel/reference/annotations These annotations are used to describe example responses for your API endpoints. You can specify the HTTP status code, provide a JSON or array example directly in the annotation, or link to an external file containing the response. ```APIDOC ## Response Annotations ### Description Used to describe example responses for API endpoints. You can specify the HTTP status code and provide the response body directly or reference a file. ### `@response` / `#[Response]` Describes an example response directly within the docblock or attributes. **Format:** `@response ` or `#[Response(, )]` **Notes:** * If no status is specified, Scribe defaults to `200`. * Supported fields: `scenario`, `status`. **Examples:** ```php // Docblock @response {"a": "b"} @response 201 {"a": "b"} @response 201 {"a": "b"} scenario="Operation successful" @response status=201 scenario="Operation successful" {"a": "b"} @response scenario=Success {"a": "b"} // Attributes #[Response('{"a": "b"}')] #[Response(['a' => 'b'])] #[Response(['a' => 'b'], 201)] #[Response('{"a": "b"}', 201, description: "Operation successful")] #[Response(['a' => 'b'], description: "Success")] public function index() {} ``` ### `@responseFile` / `#[ResponseFile]` Describes the path to a file containing an example response. The path can be absolute, relative to your project directory, or relative to your Laravel storage directory. **Format:** `@responseFile ` or `#[ResponseFile(, )]` **Notes:** * If no status is specified, Scribe defaults to `200`. * Supported fields: `scenario`, `status`. **Examples:** ```php // Docblock @responseFile /an/absolute/path @responseFile 400 relative/path/from/your/project/root @responseFile status=400 scenario="Failed" path/from/your/laravel/storage/directory @responseFile 400 scenario="Failed" path/from/your/laravel/storage/directory // Attributes #[ResponseFile("/an/absolute/path")] #[ResponseFile("relative/path/from/your/project/root", 400)] #[ResponseFile("path/from/your/laravel/storage/directory", 400, description: "Failed")] public function show() {} ``` ``` -------------------------------- ### Handling Binary Responses with @response and #[Response] Source: https://scribe.knuckles.wtf/laravel/documenting/responses Shows how to indicate a binary response (like an image) for an endpoint using the `<>` keyword. ```APIDOC ## POST /api/images ### Description This endpoint handles image uploads and returns a binary response, such as a resized image. ### Method POST ### Endpoint /api/images ### Request Body - **image** (file) - Required - The image file to upload. ### Response #### Success Response (200) - **binary** - The resized image data. ### Response Example ``` <> The resized image ``` ``` -------------------------------- ### Define Body Parameters with Attributes Source: https://scribe.knuckles.wtf/laravel/reference/annotations Use PHP 8 attributes to define request body parameters. Supports type, requirement, enum values, and examples. Nested structures can be defined using dot notation or bracket notation for arrays. 'No-example' can be passed as the example value. ```php #[BodyParam("language", "The language.", enum: ["en", "de", "fr"])] #[BodyParam("language", "The language.", enum: SupportedLanguage::class)] #[BodyParam("language", "The language.", enum: SupportedLanguage::class, example: "en")] #[BodyParam("room_id", "string")] #[BodyParam("room_id", "string", "The room ID.")] #[BodyParam("room_id", "string", "The room ID.", required: false, example: "r98639bgh3")] #[BodyParam("room_id", "string", required: false, example: "r98639bgh3")] public function endpoint() {...} // Objects and arrays #[BodyParam("user", "object", "The user data")] #[BodyParam("user.name", "string", "The user's name.")] #[BodyParam("user.age", "int", required: false, example: 1000)] #[BodyParam("people", "object[]", "List of people")] #[BodyParam("people[].name", "string", required: false, example: "Deadpool")] public function endpoint() {...} // If your entire request body is an array #[BodyParam("[]", "object[]", "List of things to do")] #[BodyParam("[].name", "string", "Name of the thing.", required: false, example: "Cook")] public function endpoint() {...} ``` -------------------------------- ### GET /healthcheck Source: https://scribe.knuckles.wtf/laravel/documenting This endpoint provides a health check for the application services. ```APIDOC ## GET /healthcheck ### Description Check that the service is up. If everything is okay, you'll get a 200 OK response. Otherwise, the request will fail with a 400 error, and a response listing the failed services. ### Method GET ### Endpoint /healthcheck ### Response #### Success Response (200) - **status** (string) - The status of this API (`up` or `down`). - **services** (map) - Map of each downstream service and their status (`up` or `down`). #### Response Example ```json { "status": "up", "services": { "database": "up", "redis": "up" } } ``` #### Error Response (400) - **status** (string) - The status of this API (`up` or `down`). - **services** (map) - Map of each downstream service and their status (`up` or `down`). #### Response Example ```json { "status": "down", "services": { "database": "up", "redis": "down" } } ``` ``` -------------------------------- ### Publish All Scribe Views Source: https://scribe.knuckles.wtf/laravel/advanced/theming Run this Artisan command to publish all vendor views for Scribe. This allows for complete customization of templates. ```bash php artisan vendor:publish --tag=scribe-views ``` -------------------------------- ### Inline Scribe Configuration Constants Source: https://scribe.knuckles.wtf/laravel/migrating Provides an alternative to using Scribe's default constants and helper methods when Scribe is a dev-only dependency. This example shows how to replace `Defaults::*_STRATEGIES` with actual values and `wrapWithSettings`/`withSettings` calls with a tuple of `[strategyName, settingsArray]`. ```php Strategies\StaticData::withSettings(data: [ 'Accept' => 'application/json', ]), [ Strategies\StaticData::class, [ 'data' => ['Accept' => 'application/json'] ] ] ``` -------------------------------- ### GET /api/users - List Users with Transformer Collection Source: https://scribe.knuckles.wtf/laravel/documenting/responses Retrieves a collection of users, formatted using a transformer. ```APIDOC ## GET /api/users ### Description Retrieves a list of all users, formatted as a collection using a transformer. ### Method GET ### Endpoint /api/users ### Response #### Success Response (200) - **[Transformer Fields]** (array) - A list of user data formatted by the `UserTransformer`. ### Response Example ```json [ { "id": 1, "name": "John Doe", "email": "john.doe@example.com" }, { "id": 2, "name": "Jane Smith", "email": "jane.smith@example.com" } ] ``` ``` -------------------------------- ### Generate Scribe Documentation Source: https://scribe.knuckles.wtf/laravel/getting-started Run the Artisan command to generate your API documentation after configuring Scribe. Visit the generated docs in your browser. ```bash php artisan scribe:generate ``` -------------------------------- ### URL Parameter Annotation Source: https://scribe.knuckles.wtf/laravel/reference/annotations Describes a URL parameter for an API endpoint, including its type, description, and example values. ```APIDOC ### `@urlParam`/`#[UrlParam]`​ Describes a URL parameter. Tag format: `@urlParam required? Enum: Example: ` Notes: * If you don't supply a `type`, `string` is assumed. * To specify allowed values for this parameter: * for tags: write "Enum: ", followed by the list of values. * for attributes: use the `enum` parameter with either a PHP 8.1 enum or an array of values. * To prevent Scribe from including this parameter in example requests: * end the description with `No-example` when using tags * pass`"No-example"`as the `example` parameter when using attributes * You can also use this on Form Request classes. Examples: * Docblock * Attributes ``` @urlParam id @urlParam id int @urlParam id int required @urlParam id int required The user's ID. @urlParam language The language. Enum: en, de, fr @urlParam language The language. Enum: en, de, fr. Example: en @urlParam id int required The user's ID. Example: 88683 @urlParam id int The user's ID. Example: 88683 @urlParam id int The user's ID. No-example ``` ``` #[UrlParam("id")] #[UrlParam("id", "int")] #[UrlParam("id", "int")] #[UrlParam("id", "int", "The user's ID.")] #[UrlParam("id", "int", "The user's ID.", example: 88683)] #[UrlParam("language", "The language.", enum: ["en", "de", "fr"])] #[UrlParam("language", "The language.", enum: SupportedLanguage::class)] #[UrlParam("language", "The language.", enum: SupportedLanguage::class, example: "en")] #[UrlParam("id", "int", "The user's ID.", required: false, example: 88683)] #[UrlParam("id", "int", "The user's ID.", required: false, example: "No-example")] public function endpoint() {...} ``` ``` -------------------------------- ### POST /api/users - User Creation with Additional Data Source: https://scribe.knuckles.wtf/laravel/documenting/responses Demonstrates how to include additional fields in the API response for user creation using API resources. ```APIDOC ## POST /api/users ### Description Creates a new user and returns the user resource with additional success information. ### Method POST ### Endpoint /api/users ### Parameters #### Request Body - **request** (object) - Required - The request payload for creating a user. ### Request Example ```json { "name": "John Doe", "email": "john.doe@example.com" } ``` ### Response #### Success Response (200) - **data** (object) - The created user resource. - **result** (string) - Indicates the outcome of the operation, e.g., "success". - **message** (string) - A message describing the outcome, e.g., "User created successfully". #### Response Example ```json { "data": { "id": 1 }, "result": "success", "message": "User created successfully" } ``` ``` -------------------------------- ### Controller Method with Custom Tag Source: https://scribe.knuckles.wtf/laravel/advanced/plugins An example of a controller method annotated with a custom '@usesPagination' tag, which can be processed by Scribe strategies. ```php class UserController { /** * @usesPagination */ public function index() { // ... } } ``` -------------------------------- ### GET /api/users/{id} - Show User with Transformer Source: https://scribe.knuckles.wtf/laravel/documenting/responses Retrieves a single user by ID using a transformer for response formatting. ```APIDOC ## GET /api/users/{id} ### Description Retrieves a specific user by their ID, formatted using a transformer. ### Method GET ### Endpoint /api/users/{id} ### Parameters #### Path Parameters - **id** (integer) - Required - The ID of the user to retrieve. ### Response #### Success Response (200) - **[Transformer Fields]** (object) - The user data formatted by the `UserTransformer`. ### Response Example ```json { "id": 1, "name": "John Doe", "email": "john.doe@example.com" } ``` ``` -------------------------------- ### Match Routes by Domain Source: https://scribe.knuckles.wtf/laravel/reference/config Limit route documentation to specific domains using the 'domains' key within the 'match' configuration. This is useful for subdomain routing. ```php 'match' => [ 'prefixes' => ['api/*'], 'domains' => ['v2.acme.co'], ], ``` -------------------------------- ### Run All Tests Source: https://scribe.knuckles.wtf/laravel/contributing Execute all tests for the Laravel project. This command will stop on the first failure encountered. ```bash composer test ``` -------------------------------- ### Install Scribe Package Source: https://scribe.knuckles.wtf/laravel Add the Scribe package to your Laravel project using Composer. Requires PHP 8.1 and Laravel 9 or higher. ```bash composer require knuckleswtf/scribe ``` -------------------------------- ### Force Full Doc Generation Source: https://scribe.knuckles.wtf/laravel/tasks/modifying Use the `--force` flag to discard any existing changes in the `.scribe` folder and start the documentation generation process afresh. This is useful when you want to ensure a clean generation without any prior modifications. ```php php artisan scribe:generate --force ``` -------------------------------- ### Generate API Docs with Scribe Source: https://scribe.knuckles.wtf/laravel/tasks/generating Run this Artisan command to extract API information and generate HTML documentation, Postman collection, and OpenAPI spec. ```bash php artisan scribe:generate ``` -------------------------------- ### Handle Binary Responses in Docblock Source: https://scribe.knuckles.wtf/laravel/documenting/responses For endpoints returning files or binary data, use `<>` as the response value in the `@response` tag, optionally followed by a description. ```php /** * @response <> The resized image */ ``` -------------------------------- ### Provide JSON Response in Docblock Source: https://scribe.knuckles.wtf/laravel/documenting/responses Use the `@response` tag within a docblock to provide a JSON example for an endpoint. The JSON can span multiple lines. ```php /** * @response { * "id": 4, * "name": "Jessica Jones", * "roles": ["admin"] * } */ public function show($id) { return User::findOrFail($id); } ``` -------------------------------- ### Paginate Resources with Attributes Source: https://scribe.knuckles.wtf/laravel/documenting/responses Use the 'paginate', 'simplePaginate', or 'cursorPaginate' arguments on #[ResponseFromApiResource] to specify pagination for resource collections. ```php #[ResponseFromApiResource(UserCollection::class, User::class, paginate: 10)] public function listMoreUsers() { return new UserCollection(User::paginate(10)); } #[ResponseFromApiResource(UserCollection::class, User::class, simplePaginate: 15)] public function listMoreUsers() { return new UserCollection(User::simplePaginate(15)); } #[ResponseFromApiResource(UserCollection::class, User::class, cursorPaginate: 15)] public function listMoreUsers() { return new UserCollection(User::cursorPaginate(15)); } ``` -------------------------------- ### Response Field Examples Source: https://scribe.knuckles.wtf/laravel/documenting/responses Demonstrates how Scribe handles response field annotations for simple JSON objects, arrays of objects, and paginated responses where the field is nested. ```json { "id": 3 } ``` ```json [ { "id": 3 } ] ``` ```json { "data": [ { "id": 3 } ] } ``` -------------------------------- ### Define Request Header with Docblock Tag Source: https://scribe.knuckles.wtf/laravel/reference/annotations Use the @header tag in your docblocks to describe request headers. You can specify the header name and an optional example value. ```php @header Api-Version ``` ```php @header Content-Type application/xml ``` -------------------------------- ### Handle Binary Responses with Attributes Source: https://scribe.knuckles.wtf/laravel/documenting/responses Use `<>` as the content for the `#[Response]` attribute when the endpoint returns binary data, followed by an optional description. ```php #[Response("<>", "The resized image")] ``` -------------------------------- ### Displaying a Badge Component Source: https://scribe.knuckles.wtf/laravel/advanced/theming Example of using a Blade component to display a badge with custom text and color. This component is located within the published Scribe views. ```blade @component('scribe::components.badges.base', [ 'colour' => "darkred", 'text' => 'requires authentication' ]) ```