### Development Setup Source: https://github.com/moon0326/wp-openapi/blob/main/readme.md Instructions for setting up the development environment for WP OpenAPI, including installing dependencies and starting the development server. ```APIDOC ## Development ### Getting Started To get started, run the following commands: ```bash npm i composer install npm start ``` See [wp-scripts](https://github.com/WordPress/gutenberg/tree/master/packages/scripts) for more usage information. ### Deploying Prerequisites: - [Hub](https://github.com/github/hub) - Write access to this repository 1. Run both `npm i` and `composer install` 2. Update the plugin version in [wp-openapi.php](https://github.com/moon0326/wp-openapi/blob/main/wp-openapi.php) and [readme.txt](https://github.com/moon0326/wp-openapi/blob/main/readme.txt#L7) 3. Update `Tested up to` in readme.txt if necessary. 3. Open a new PR and merge it. 4. Checkout `main` branch locally. 4. Run `./bin/release-to-github.sh`. This will create a new release in Github 5. Run `./bin/release-plugin-to-dot-org.sh` to release the new version to wp.org You can also build a zip file for testing purposes by runnning `./bin/build-zip.sh` ``` -------------------------------- ### Development Setup Commands (Shell) Source: https://github.com/moon0326/wp-openapi/blob/main/readme.md Lists the essential commands to set up the development environment for WP OpenAPI, including installing Node.js and Composer dependencies, and starting the development server. ```shell npm i composer install npm start ``` -------------------------------- ### Register REST Route with Security Field (PHP) Source: https://github.com/moon0326/wp-openapi/blob/main/readme.md Shows how to register a WordPress REST API route and apply the defined security scheme. This example uses an 'api_key' security scheme for a GET request. ```php register_rest_route( $this->namespace, '/' . $this->rest_base . '/test', array( array( 'methods' => 'GET', 'callback' => array( $this, 'test' ), 'args' => array( 'status' => array( 'type' => 'string', 'enum' => array( 'yes', 'no' ), ), 'credentials' => array( 'type' => 'object', 'properties' => array( 'username' => array( 'type' => 'string' ), 'application_password'=> array( 'type' => 'string' ), ), ), ), 'security' => array( 'api_key' => array(), ), ), ) ); ``` -------------------------------- ### Register WordPress REST Route with OpenAPI Args (PHP) Source: https://context7.com/moon0326/wp-openapi/llms.txt Shows how to register a custom WordPress REST route using `register_rest_route`. It details defining arguments for GET, POST, and DELETE methods, including types, requirements, descriptions, enums, and security. It also demonstrates defining a schema for the route. ```php [\d]+)', [ [ 'methods' => 'GET', 'callback' => 'get_item_callback', 'permission_callback' => '__return_true', 'description' => 'Retrieve a single item by ID', 'args' => [ 'id' => [ 'type' => 'integer', 'required' => true, 'description' => 'Unique identifier for the item', 'minimum' => 1, ], 'context' => [ 'type' => 'string', 'enum' => ['view', 'edit', 'embed'], 'default' => 'view', 'description' => 'Scope under which the request is made', ], ], ], [ 'methods' => 'POST', 'callback' => 'update_item_callback', 'permission_callback' => 'can_edit_items', 'description' => 'Update an existing item', 'args' => [ 'id' => [ 'type' => 'integer', 'required' => true, 'description' => 'Unique identifier for the item', ], 'title' => [ 'type' => 'string', 'required' => true, 'description' => 'Item title', 'minLength' => 1, 'maxLength' => 255, ], 'status' => [ 'type' => 'string', 'enum' => ['draft', 'published', 'archived'], 'default' => 'draft', ], 'metadata' => [ 'type' => 'object', 'description' => 'Additional item metadata', 'properties' => [ 'author' => ['type' => 'string'], 'tags' => [ 'type' => 'array', 'items' => ['type' => 'string'], ], ], ], ], 'security' => [ 'bearer_auth' => [], ], ], [ 'methods' => 'DELETE', 'callback' => 'delete_item_callback', 'permission_callback' => 'can_delete_items', 'description' => 'Delete an item permanently', 'args' => [ 'id' => [ 'type' => 'integer', 'required' => true, ], 'force' => [ 'type' => 'boolean', 'default' => false, 'description' => 'Skip trash and delete permanently', ], ], ], 'schema' => function() { return [ 'title' => 'Item', 'type' => 'object', 'properties' => [ 'id' => ['type' => 'integer', 'description' => 'Unique identifier'], 'title' => ['type' => 'string', 'description' => 'Item title'], 'status' => ['type' => 'string', 'enum' => ['draft', 'published', 'archived']], 'created_at' => ['type' => 'string', 'format' => 'date-time'], ], ]; }, ]); ``` -------------------------------- ### Get OpenAPI Schema Source: https://context7.com/moon0326/wp-openapi/llms.txt This endpoint returns the OpenAPI specification as JSON. You can retrieve the schema for all namespaces or filter by a specific namespace. ```APIDOC ## GET /wp-json/wp-openapi/v1/schema ### Description Retrieves the OpenAPI 3.1.0 schema for registered WordPress REST API routes. ### Method GET ### Endpoint `/wp-json/wp-openapi/v1/schema` ### Query Parameters - **namespace** (string) - Optional - Filters the schema to include only routes within the specified namespace (e.g., `wp/v2`). ### Request Example ```bash # Get OpenAPI spec for all namespaces curl https://your-site.com/wp-json/wp-openapi/v1/schema # Get OpenAPI spec for a specific namespace curl https://your-site.com/wp-json/wp-openapi/v1/schema?namespace=wp/v2 # Alternative pretty URL (requires permalink rewrite) curl https://your-site.com/wp-json-openapi ``` ### Response #### Success Response (200) - **schema** (object) - The OpenAPI 3.1.0 specification in JSON format. #### Response Example ```json { "openapi": "3.1.0", "info": { "title": "WordPress REST API", "version": "1.0.0" }, "paths": { "/wp/v2/posts": { "get": { "summary": "Get posts", "parameters": [], "responses": { "200": { "description": "Success" } } } } } } ``` ``` -------------------------------- ### Control WP OpenAPI Schema Endpoint Permissions Source: https://context7.com/moon0326/wp-openapi/llms.txt This PHP code provides examples of how to control access to the WP OpenAPI schema endpoint using the `wp-openapi-filters-schema-endpoint-permission` filter. It demonstrates restricting access to logged-in users, administrators only, or based on custom criteria like IP addresses or API keys. The default behavior allows public access. ```php getEndpoint() === '/wp/v2/posts' && $operation->getMethod() === 'post' ) { // Get the existing schema. $schema = $request_body['content']['application/x-www-form-urlencoded']['schema']; // Return a new request body with 'application/json'. return [ 'content' => [ 'application/json' => [ 'schema' => $schema, ], ], ]; } // Return the original request body for all other endpoints. return $request_body; }, 10, 2 ); ``` -------------------------------- ### Deployment Script Commands (Shell) Source: https://github.com/moon0326/wp-openapi/blob/main/readme.md Outlines the shell commands used for deploying the WP OpenAPI project, including building a zip file for testing and releasing to GitHub and WordPress.org. ```shell ./bin/release-to-github.sh ./bin/release-plugin-to-dot-org.sh ./bin/build-zip.sh ``` -------------------------------- ### Registering Routes with OpenAPI Schema Source: https://context7.com/moon0326/wp-openapi/llms.txt Illustrates how to define WordPress REST routes with argument definitions that map to OpenAPI parameters and request body schemas. ```APIDOC ## Registering Routes with OpenAPI Schema Define WordPress REST routes with proper argument definitions that translate to OpenAPI parameters and request body schemas. ### Method `register_rest_route` function in PHP. ### Description This example shows how to register a REST route for handling items. It defines GET, POST, and DELETE methods, each with specific arguments, permissions, and descriptions. The `schema` callback provides a schema definition for the item resource. ### Endpoint `/myplugin/v1/items/(?P[\d]+)` ### Parameters #### Path Parameters - **id** (integer) - Required - Unique identifier for the item #### Query Parameters (for GET request) - **context** (string) - Optional - Scope under which the request is made. Enum: `view`, `edit`, `embed`. Default: `view` #### Request Body (for POST request) - **id** (integer) - Required - Unique identifier for the item - **title** (string) - Required - Item title. MinLength: 1, MaxLength: 255 - **status** (string) - Optional - Item status. Enum: `draft`, `published`, `archived`. Default: `draft` - **metadata** (object) - Optional - Additional item metadata. - **author** (string) - Optional - **tags** (array) - Optional - Array of strings #### Query Parameters (for DELETE request) - **force** (boolean) - Optional - Skip trash and delete permanently. Default: `false` ### Request Example (POST) ```php [\d]+)', [ // ... (GET and DELETE methods defined here) [ 'methods' => 'POST', 'callback' => 'update_item_callback', 'permission_callback' => 'can_edit_items', 'description' => 'Update an existing item', 'args' => [ 'id' => [ 'type' => 'integer', 'required' => true, 'description' => 'Unique identifier for the item', ], 'title' => [ 'type' => 'string', 'required' => true, 'description' => 'Item title', 'minLength' => 1, 'maxLength' => 255, ], 'status' => [ 'type' => 'string', 'enum' => ['draft', 'published', 'archived'], 'default' => 'draft', ], 'metadata' => [ 'type' => 'object', 'description' => 'Additional item metadata', 'properties' => [ 'author' => ['type' => 'string'], 'tags' => [ 'type' => 'array', 'items' => ['type' => 'string'], ], ], ], ], 'security' => [ 'bearer_auth' => [], ], ], // ... (DELETE method defined here) 'schema' => function() { return [ 'title' => 'Item', 'type' => 'object', 'properties' => [ 'id' => ['type' => 'integer', 'description' => 'Unique identifier'], 'title' => ['type' => 'string', 'description' => 'Item title'], 'status' => ['type' => 'string', 'enum' => ['draft', 'published', 'archived']], 'created_at' => ['type' => 'string', 'format' => 'date-time'], ], ]; }, ]); ``` ### Response #### Success Response (200) - **id** (integer) - Unique identifier - **title** (string) - Item title - **status** (string) - Item status (e.g., 'draft', 'published', 'archived') - **created_at** (string) - Timestamp of creation (format: date-time) #### Response Example (GET /items/{id}) ```json { "id": 123, "title": "Sample Item", "status": "published", "created_at": "2023-10-27T10:00:00+00:00" } ``` ``` -------------------------------- ### Customize OpenAPI Output with Filters in PHP Source: https://context7.com/moon0326/wp-openapi/llms.txt Illustrates how to use the `Filters` class singleton to register custom filters for modifying various aspects of the generated OpenAPI specification, such as paths, operations, server URLs, info, tags, and components. ```php addPathsFilter(function(array $paths, array $args) { foreach ($paths as $path) { foreach ($path->getOperations() as $operation) { $operation->setDescription('Custom description'); } } return $paths; }, 10); // Add a filter to modify operations $filters->addOperationsFilter(function(array $operations, array $args) { foreach ($operations as $operation) { $operation->setSummary('Modified summary'); } return $operations; }, 10); // Add a filter to modify server URLs $filters->addServersFilter(function(array $servers, array $args) { $servers[] = new \WPOpenAPI\Spec\Server('https://staging.example.com/wp-json'); return $servers; }, 10); // Add a filter to modify API info $filters->addInfoFilter(function(\WPOpenAPI\Spec\Info $info, array $args) { $info->setSummary('My Custom API'); $info->setTermsOfService('https://example.com/terms'); return $info; }, 10); // Add a filter to modify tags $filters->addTagsFilter(function(array $tags, array $args) { foreach ($tags as $tag) { $tag->setDescription('Namespace: ' . $tag->getName()); } return $tags; }, 10); // Add a filter to modify components (schemas, security schemes) $filters->addComponentsFilter(function(array $components, array $args) { $components['securitySchemes'] = [ 'bearerAuth' => [ 'type' => 'http', 'scheme' => 'bearer', ], ]; return $components; }, 10); ``` -------------------------------- ### Export OpenAPI Spec with WP-CLI (Bash) Source: https://context7.com/moon0326/wp-openapi/llms.txt Provides WP-CLI commands to export the OpenAPI specification in various formats (HTML, JSON) and for different namespaces. This allows for offline use or hosting the API documentation externally. ```bash # Export all namespaces as HTML wp openapi export --namespace=all --save_to=./api-docs.html # Export specific namespace as HTML wp openapi export --namespace=wp/v2 --save_to=./wp-v2-docs.html # Export as JSON wp openapi export --namespace=all --save_to=./openapi.json --format=json # Export WooCommerce API documentation wp openapi export --namespace=wc/v3 --save_to=./woocommerce-api.html # Export custom plugin API wp openapi export --namespace=myplugin/v1 --save_to=./myplugin-api.json --format=json ``` -------------------------------- ### Add Security Schemes to OpenAPI Specification in PHP Source: https://context7.com/moon0326/wp-openapi/llms.txt Explains how to add security schemes (e.g., API key, Bearer token, Basic auth) to the OpenAPI specification by filtering the components and then referencing these schemes in individual REST route registrations. ```php [ 'type' => 'apiKey', 'name' => 'X-API-Key', 'in' => 'header', ], 'bearer_auth' => [ 'type' => 'http', 'scheme' => 'bearer', 'bearerFormat' => 'JWT', ], 'basic_auth' => [ 'type' => 'http', 'scheme' => 'basic', ], ]; return $components; }); // Step 2: Reference security in route registration register_rest_route('myplugin/v1', '/secure-endpoint', [ [ 'methods' => 'GET', 'callback' => 'my_secure_callback', 'permission_callback' => 'my_permission_check', 'args' => [ 'id' => [ 'type' => 'integer', 'required' => true, 'description' => 'Resource ID', ], ], 'security' => [ 'api_key' => [], 'bearer_auth' => [], ], ], ]); // Expected OpenAPI output for the endpoint: // { // "/myplugin/v1/secure-endpoint": { // "get": { // "security": [ // {"api_key": []}, // {"bearer_auth": []} // ], // "parameters": [...] // } // } // } ``` -------------------------------- ### Adding Security Schemes Source: https://context7.com/moon0326/wp-openapi/llms.txt Security schemes must be added via the `components` filter. Once defined, they can be referenced in individual route registrations. ```APIDOC ## Adding Security Schemes ### Description This section details how to define and apply security schemes (e.g., API Key, Bearer Token, Basic Auth) to your WordPress REST API endpoints using WP OpenAPI. ### Step 1: Add Security Schemes to Components Use the `wp-openapi-filter-components` filter to define your security schemes. These schemes will be available in the `components.securitySchemes` section of your OpenAPI specification. ### Step 2: Reference Security in Route Registration When registering a REST route using `register_rest_route`, include a `security` key in the route definition. This key should be an array where keys are the names of the security schemes defined in Step 1, and values are typically empty arrays or specific parameters required by the scheme. ### Request Example (PHP) ```php [ 'type' => 'apiKey', 'name' => 'X-API-Key', 'in' => 'header', ], 'bearer_auth' => [ 'type' => 'http', 'scheme' => 'bearer', 'bearerFormat' => 'JWT', ], 'basic_auth' => [ 'type' => 'http', 'scheme' => 'basic', ], ]; return $components; }); // Step 2: Reference security in route registration register_rest_route('myplugin/v1', '/secure-endpoint', [ [ 'methods' => 'GET', 'callback' => 'my_secure_callback', 'permission_callback' => 'my_permission_check', 'args' => [ 'id' => [ 'type' => 'integer', 'required' => true, 'description' => 'Resource ID', ], ], 'security' => [ 'api_key' => [], 'bearer_auth' => [], ], ], ]); ``` ### Expected OpenAPI Output Snippet ```json { "/myplugin/v1/secure-endpoint": { "get": { "security": [ {"api_key": []}, {"bearer_auth": []} ], "parameters": [ { "name": "id", "in": "query", "required": true, "schema": { "type": "integer" }, "description": "Resource ID" } ] } } } ``` ``` -------------------------------- ### Export OpenAPI Specification using WP-CLI (Shell) Source: https://github.com/moon0326/wp-openapi/blob/main/readme.md Provides the command to export the OpenAPI specification as a single HTML file using WP-CLI. This is useful for offline viewing or hosting the specification separately. ```shell wp openapi export --namespace=all --save_to=./export.html ``` -------------------------------- ### Generate OpenAPI Spec with SchemaGenerator (PHP) Source: https://context7.com/moon0326/wp-openapi/llms.txt Demonstrates how to instantiate and use the SchemaGenerator class to programmatically generate an OpenAPI specification from WordPress REST routes. It covers generating specs for all namespaces or specific ones and outputting the result as JSON. ```php get_option('admin_email'), 'blogname' => get_option('blogname'), 'blogdescription' => get_option('blogdescription'), 'home' => get_option('home'), 'wp_version' => $wp_version, ]; $restServer = rest_get_server(); $hooks = Filters::getInstance(); $schemaGenerator = new SchemaGenerator($hooks, $siteInfo, $restServer); // Generate spec for all namespaces $allSpec = $schemaGenerator->generate('all'); // Generate spec for specific namespace $wpSpec = $schemaGenerator->generate('wp/v2'); // Output as JSON header('Content-Type: application/json'); echo json_encode($allSpec, JSON_PRETTY_PRINT); // Expected output structure: // { // "openapi": "3.1.0", // "info": { // "title": "My Site API", // "version": "6.4", // "description": "Site description" // }, // "servers": [{"url": "https://example.com/wp-json"}], // "paths": {...}, // "tags": [...], // "components": {"schemas": {...}} // } ``` -------------------------------- ### SchemaGenerator Usage Source: https://context7.com/moon0326/wp-openapi/llms.txt Demonstrates how to use the SchemaGenerator class to programmatically generate OpenAPI specifications from WordPress REST routes. ```APIDOC ## Schema Generator Usage The `SchemaGenerator` class is the core component that generates the OpenAPI specification from WordPress REST routes. ### Method Programmatic generation using PHP. ### Description This code snippet shows how to instantiate `SchemaGenerator` and generate OpenAPI specs for all namespaces or specific ones. The generated spec can then be outputted as JSON. ### Request Example ```php get_option('admin_email'), 'blogname' => get_option('blogname'), 'blogdescription' => get_option('blogdescription'), 'home' => get_option('home'), 'wp_version' => $wp_version, ]; $restServer = rest_get_server(); $hooks = Filters::getInstance(); $schemaGenerator = new SchemaGenerator($hooks, $siteInfo, $restServer); // Generate spec for all namespaces $allSpec = $schemaGenerator->generate('all'); // Generate spec for specific namespace $wpSpec = $schemaGenerator->generate('wp/v2'); // Output as JSON header('Content-Type: application/json'); echo json_encode($allSpec, JSON_PRETTY_PRINT); ``` ### Response Example ```json { "openapi": "3.1.0", "info": { "title": "My Site API", "version": "6.4", "description": "Site description" }, "servers": [{"url": "https://example.com/wp-json"}], "paths": {...}, "tags": [...], "components": {"schemas": {...}} } ``` ``` -------------------------------- ### Export API Documentation Source: https://github.com/moon0326/wp-openapi/blob/main/readme.md WP OpenAPI provides a WP-CLI command to export your API documentation as a single HTML file, which can be used offline or hosted. ```APIDOC ## Export WP OpenAPI comes with a [WP CLI](https://wp-cli.org/) command to export a single HTML file. You can use the file offline or host it on a webserver. 1. Install [WP CLI](https://wp-cli.org/) 2. Open a terminal session and cd to your WordPress installtion directory. 3. Run `wp openapi export --namespace=all --save_to=./export.html` ### Method WP-CLI Command ### Endpoint N/A ### Parameters #### Command Arguments - **--namespace** (string) - Required - The namespace of the API to export. Use 'all' for all namespaces. - **--save_to** (string) - Required - The path to save the exported HTML file. ``` -------------------------------- ### Enable Callback Discovery in WP OpenAPI Source: https://context7.com/moon0326/wp-openapi/llms.txt This PHP snippet shows how to enable callback discovery within the WP OpenAPI plugin. Enabling this feature allows the plugin to display source code information for each API endpoint in the documentation. This includes the callback type, callable name, and the file path where the callback is defined, aiding in debugging and understanding endpoint logic. ```php 'on', ]); // The plugin adds callback info to operation descriptions: // - Callback type (function, method, closure) // - Callable name // - File path where the callback is defined // Example output in description: // "Get all posts. // Callback: WP_REST_Posts_Controller::get_items // File: /var/www/html/wp-includes/rest-api/endpoints/class-wp-rest-posts-controller.php" ``` -------------------------------- ### Add Security Schemes using wp-openapi-filter-components (PHP) Source: https://github.com/moon0326/wp-openapi/blob/main/readme.md Demonstrates how to add custom security schemes to the OpenAPI components using the 'wp-openapi-filter-components' filter in PHP. This allows for defining authentication methods like API keys. ```php add_filter( 'wp-openapi-filter-components', function( array $components ) { $components['securitySchemes'] = array( 'api_key' => array( 'type' => 'apiKey', 'name' => 'api_key', 'in' => 'header', ), ); return $components; } ); ``` -------------------------------- ### Modify Path Operations and Descriptions (PHP) Source: https://context7.com/moon0326/wp-openapi/llms.txt Allows modification of endpoint documentation, addition of custom descriptions, and filtering of specific endpoints from the generated OpenAPI specification. It uses the 'addPathsFilter' method from WPOpenAPI\Filters to hook into the path modification process. ```php addPathsFilter(function(array $paths, array $args) { $requestedNamespace = $args['requestedNamespace']; foreach ($paths as $pathKey => $path) { // Skip internal endpoints if (str_contains($path->getPath(), '/internal/')) { unset($paths[$pathKey]); continue; } foreach ($path->getOperations() as $operation) { // Add deprecation notice to old endpoints if (str_contains($path->getPath(), '/v1/')) { $operation->setDescription( '**DEPRECATED**: ' . $operation->getDescription() . ' Please use v2 endpoints instead.' ); } // Add namespace tag $operation->addTag($requestedNamespace); // Set operation ID based on method and path $operationId = $operation->getMethod() . '_' . str_replace(['/', '{', '}', '-'], ['_', '', '', '_'], $path->getPath()); $operation->setOperationId($operationId); } } return $paths; }, 10); ?> ``` -------------------------------- ### Filters Class - Customizing OpenAPI Output Source: https://context7.com/moon0326/wp-openapi/llms.txt The `Filters` class provides a singleton instance to register and apply filters for customizing the generated OpenAPI specification. ```APIDOC ## Filters Class ### Description Provides methods to register filters for customizing various aspects of the OpenAPI specification, such as paths, operations, servers, info, tags, and components. ### Usage Use the singleton instance `Filters::getInstance()` to add custom filter callbacks. ### Filters Available - **`addPathsFilter`**: Modifies the paths object. - **`addOperationsFilter`**: Modifies individual operations within paths. - **`addServersFilter`**: Modifies the server URLs. - **`addInfoFilter`**: Modifies the API information object. - **`addTagsFilter`**: Modifies the tags object. - **`addComponentsFilter`**: Modifies the components object (schemas, security schemes, etc.). ### Request Example (PHP) ```php addPathsFilter(function(array $paths, array $args) { // Modify $paths array return $paths; }, 10); // Add a filter to modify operations $filters->addOperationsFilter(function(array $operations, array $args) { // Modify $operations array return $operations; }, 10); // Add a filter to modify server URLs $filters->addServersFilter(function(array $servers, array $args) { // Modify $servers array return $servers; }, 10); // Add a filter to modify API info $filters->addInfoFilter(function(WPOpenAPI\Spec\Info $info, array $args) { // Modify $info object return $info; }, 10); // Add a filter to modify tags $filters->addTagsFilter(function(array $tags, array $args) { // Modify $tags array return $tags; }, 10); // Add a filter to modify components $filters->addComponentsFilter(function(array $components, array $args) { // Modify $components array return $components; }, 10); ``` ``` -------------------------------- ### Fetch OpenAPI Schema using cURL Source: https://context7.com/moon0326/wp-openapi/llms.txt Demonstrates how to retrieve the OpenAPI specification JSON from the WordPress REST API endpoint using cURL. Supports fetching the entire schema or filtering by a specific namespace. ```bash # Get OpenAPI spec for all namespaces curl https://your-site.com/wp-json/wp-openapi/v1/schema # Get OpenAPI spec for a specific namespace curl https://your-site.com/wp-json/wp-openapi/v1/schema?namespace=wp/v2 # Alternative pretty URL (requires permalink rewrite) curl https://your-site.com/wp-json-openapi ``` -------------------------------- ### Manage WP OpenAPI Settings Programmatically Source: https://context7.com/moon0326/wp-openapi/llms.txt This PHP code illustrates how to access and modify WP OpenAPI plugin settings programmatically using the `SettingsPage` class. It shows how to retrieve individual option values and how to set multiple options at once using `update_option`. This allows for dynamic configuration of plugin features based on application logic. ```php 'on', 'enableCallbackDiscovery' => 'on', 'enableACFIntegration' => 'on', ]); // Conditional logic based on settings if (SettingsPage::getOption('enableTryIt') === 'on') { // Try It feature is enabled in the Elements viewer } ``` -------------------------------- ### Security Field Configuration Source: https://github.com/moon0326/wp-openapi/blob/main/readme.md This section explains how to add security schemes to your WordPress REST API using the `wp-openapi-filter-components` filter and how to apply them to specific routes. ```APIDOC ## Using security field Since there is no central place to add `securitySchemes` in WordPress, you can use the `wp-openapi-filter-components` filter to add them. ```php add_filter( 'wp-openapi-filter-components', function( array $components ) { $components['securitySchemes'] = array( 'api_key' => array( 'type' => 'apiKey', 'name' => 'api_key', 'in' => 'header', ), ); return $components; } ); ``` Now, you can use the `security` field in your REST API definition. ```php register_rest_route( $this->namespace, '/' . $this->rest_base . '/test', array( array( 'methods' => 'GET', 'callback' => array( $this, 'test' ), 'args' => array( 'status' => array( 'type' => 'string', 'enum' => array( 'yes', 'no' ), ), 'credentials' => array( 'type' => 'object', 'properties' => array( 'username' => array( 'type' => 'string' ), 'application_password'=> array( 'type' => 'string' ), ), ), ), 'security' => array( 'api_key' => array(), ), ), ) ); ``` ### Method GET ### Endpoint /wp-json/your-namespace/your-rest-base/test ### Parameters #### Query Parameters - **status** (string) - Optional - Can be 'yes' or 'no'. #### Request Body - **credentials** (object) - Optional - Contains user credentials. - **username** (string) - Required - The username. - **application_password** (string) - Required - The application password. ### Request Example ```json { "credentials": { "username": "example_user", "application_password": "app_password_123" } } ``` ### Response #### Success Response (200) - **message** (string) - A success message. #### Response Example ```json { "message": "Test successful" } ``` ``` -------------------------------- ### Customize API Information (PHP) Source: https://context7.com/moon0326/wp-openapi/llms.txt Enables customization of the API information section, including title, description, contact details, license, and terms of service. It utilizes the 'wp-openapi-filter-info' filter to modify the Info object. ```php setSummary('Production REST API for ' . get_bloginfo('name')); // Add terms of service URL $info->setTermsOfService('https://example.com/api-terms'); // Add license information $license = new License('MIT', 'https://opensource.org/licenses/MIT'); $info->setLicense($license); return $info; }, 10, 2); // Access info properties add_filter('wp-openapi-filter-info', function(\WPOpenAPI\Spec\Info $info, array $args) { $contact = $info->getContact(); // Contact includes: name, url, email from WordPress settings return $info; }, 20, 2); ?> ``` -------------------------------- ### Customize Stoplight Elements Viewer Props Source: https://context7.com/moon0326/wp-openapi/llms.txt This PHP filter allows customization of the props passed to the Stoplight Elements viewer component used by the WP OpenAPI plugin. You can modify viewer options such as hiding the 'Try It' functionality, controlling schema visibility, and setting the router type. It also demonstrates how to alter the schema endpoint URL. ```php 'myplugin/v1', ], rest_url('wp-openapi/v1/schema')); return $data; }); ``` -------------------------------- ### Extend WP OpenAPI Paths with PHP Filter Source: https://github.com/moon0326/wp-openapi/blob/main/readme.md This PHP code snippet demonstrates how to use the `addPathsFilter` from the `Filters` class to modify OpenAPI path definitions. It targets all endpoints when 'all' is specified as the requested namespace and sets a description for each operation. ```php Filters::getInstance()->addPathsFilter( function( array $paths, array $args ) { if ( $args['requestedNamespace'] === 'all' ) { foreach ( $paths as $path ) { foreach ( $path->getOperations() as $operation ) { $operation->setDescription( 'test' ); } } } } ); ``` -------------------------------- ### Enable ACF Integration in WP OpenAPI Source: https://context7.com/moon0326/wp-openapi/llms.txt This snippet demonstrates how to enable the ACF integration for the WP OpenAPI plugin. When enabled, the plugin automatically discovers and includes ACF field schemas in the OpenAPI output for posts with ACF fields. This integration enhances the OpenAPI schema by adding an 'acf' property to component schemas and request bodies. ```php 'on', ]); // The plugin will automatically: // 1. Perform OPTIONS requests to discover ACF schemas // 2. Add 'acf' property to component schemas // 3. Add 'acf' to request body schemas for POST/PUT/PATCH operations // Example output with ACF fields: // { // "components": { // "schemas": { // "post": { // "properties": { // "id": {"type": "integer"}, // "title": {"type": "object"}, // "acf": { // "type": "object", // "properties": { // "custom_field": {"type": "string"}, // "repeater_field": { // "type": "array", // "items": {...} // } // } // } // } // } // } // } // } ``` -------------------------------- ### Change Request Body Content Type to JSON (PHP) Source: https://context7.com/moon0326/wp-openapi/llms.txt Modifies the default 'application/x-www-form-urlencoded' content type for request bodies to 'application/json' for specific endpoints and methods. This is useful for APIs that expect JSON payloads. It uses the 'wp_openapi_operation_request_body' filter. ```php getEndpoint() === '/wp/v2/posts' && in_array($operation->getMethod(), ['post', 'put', 'patch'])) { $schema = $request_body['content']['application/x-www-form-urlencoded']['schema']; return [ 'content' => [ 'application/json' => [ 'schema' => $schema, ], ], ]; } // Support multiple content types for a custom endpoint if (str_starts_with($operation->getEndpoint(), '/myplugin/v1/')) { $schema = $request_body['content']['application/x-www-form-urlencoded']['schema']; return [ 'content' => [ 'application/json' => ['schema' => $schema], 'multipart/form-data' => ['schema' => $schema], ], ]; } return $request_body; }, 10, 2); ?> ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.