PHP code example of organiseyou / openapi-generator
1. Go to this page and download the library: Download organiseyou/openapi-generator library. Choose the download type require.
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
$api->path('/users/{id}')
->method('GET')
->summary('Get a specific user')
->description('Retrieve a user by their ID')
->tags(['Users'])
->parameters([
[
'name' => 'id',
'in' => 'path',
'['$ref' => '#/components/schemas/User']
]
]
])
->response(404, ['description' => 'User not found'])
->register();
$json = $api->toJson();
// or with custom flags:
$json = $api->toJson(JSON_PRETTY_PRINT);
$spec = $api->generate();
$yaml = $api->toYaml();
// routes/api.php
Route::get('/docs', function () {
$api = new OpenApiService('My API', '1.0.0');
// Define your schemas and endpoints
$api->schema('User')->type('object')->property('id', 'integer')->register();
$api->path('/users')->method('GET')->response(200, [])->register();
return response()->json($api->generate());
});
namespace App\Services;
use OrganiseYou\OpenApi\OpenApiService;
class ApiDocumentationService
{
public static function generate(): OpenApiService
{
$api = new OpenApiService(
title: config('app.name'),
version: '1.0.0',
basePath: '/api/v1'
);
// Define your schemas and endpoints here
self::defineUserSchema($api);
self::defineUserEndpoints($api);
return $api;
}
private static function defineUserSchema(OpenApiService $api): void
{
$api->schema('User')
->type('object')
->property('id', 'integer')
->property('name', 'string')
->property('email', 'string')
->
namespace App\Http\Controllers;
use App\Services\ApiDocumentationService;
class ApiDocumentationController extends Controller
{
public function show()
{
$api = ApiDocumentationService::generate();
return response()->json($api->generate());
}
}