This guide defines how to generate a complete PHP SDK from any valid Swagger/OpenAPI specification. It is used by AI coding assistants and tools integrated with Context7 to create versioned, testable, and PSR-compliant SDKs for PHP projects.
swagger_url
: A valid public or private URL to a Swagger documentinfo.title
: Used to derive the Composer vendor name and PHP namespaceinfo.description
: Used as the SDK description
The generated SDK will be placed into generated-sdk
and follow this structure:
generated-sdk/
βββ composer.json
βββ src/
β βββ v1/
β βββ Services/
β β βββ {Tag}Service.php
β βββ Models/
β β βββ DTO/
β β β βββ {Model}.php
β β βββ Enums/
β β βββ {Enum}.php
β βββ Exceptions/
β βββ {Exception}.php
βββ tests/
β βββ Unit/v1/Services/
β β βββ {Service}Test.php
β βββ Feature/v1/
β βββ {Tag}Test.php
βββ README.md
Each API tag becomes a service class (e.g., UsersService
). Methods are generated from operationId
, and constructor dependencies include:
GuzzleHttp\ClientInterface
string $apiKey
(ifBearer
auth is required)
Each OpenAPI schema is converted to a PHP class with:
- CamelCase properties
- Constructor accepting an array of data
- Optional getters/setters
OpenAPI enums are generated as PHP 8.1+ native enums:
enum Status: string {
case ACTIVE = 'active';
case INACTIVE = 'inactive';
}
Each API error response (e.g., 401 Unauthorized
) generates an exception:
class UnauthorizedException extends ApiException
All custom exceptions extend ApiException
.
Tests are generated using Pest-compatible PHPUnit files:
Unit
tests mock Guzzle responsesFeature
tests simulate real API responses (optional)
Swagger Type | PHP Type |
---|---|
string | string |
integer | int |
boolean | bool |
number | float |
array | array |
object | {Class} |
enum | {Enum} |
Templates are used to render actual PHP code for services, DTOs, enums, and exceptions. These templates include:
composer.json
- Service class methods with annotations and Guzzle usage
- DTO class with typed properties and parsing logic
- Enums with all values listed
- Base and custom exception classes
- Unit test cases with mock expectations
use context7
Generate a PHP SDK using FromSwaggerToPHPSDK instructions:
https://example.com/api/docs/
- All code is generated using PHP 8.1+ syntax
- The SDK supports PSR-4 autoloading for easy integration
- The structure allows versioning (e.g.,
v1
,v2
folders)
Version: 1.0.0
Language: PHP
Context: Context7 β FromSwaggerToPHPSDK