swagger-php icon indicating copy to clipboard operation
swagger-php copied to clipboard

Possible to include ref not visible to public in generated spec?

Open blueblakk opened this issue 2 years ago • 4 comments

If I have a few JSON schema's defined in my backend not directly visible to the public, is there a way I could refer to those in my code and have the OpenApi generator somehow include the contents of it in the generated document?

/**
 * @OA\Post(
 *     path="/api/v1/test",
 *     @OA\RequestBody(
 *         @OA\JsonContent(ref="/not/visible/to/public/body.json")
 *     ),
 *     @OA\Response(
 *         response=HttpCode::STATUS_NO_CONTENT,
 *         description="Succesfully created."
 *     )
 * )
 */

blueblakk avatar Sep 02 '23 20:09 blueblakk

Hmm, not really, sorry.

DerManoMann avatar Sep 07 '23 22:09 DerManoMann

this would come in handy if you have larger requests/responses and want to store them outside of the controller is there any other possibility to include (json)content of external files?

erik-re avatar Sep 08 '23 07:09 erik-re

@erik-re You can use the PHP classes as schema if your responses are large, it will help you to keep it isolated and manageable for large schema. For e.g

SchemaYourSchemaNameClass.php

use OpenApi\Attributes\Property;
use OpenApi\Attributes\Schema;

#[Schema()]
class SchemaYourSchemaNameClass
{
    #[Property()]
    public int $productId;

    #[Property()]
    public string $name;
}

Now you can use this for your response.

use OpenApi\Attributes\Schema;
use OpenApi\Attributes\JsonContent;

#[Response(
    response: 'YourResponse',
    description: 'description',
    content: new JsonContent(
       ref: SchemaYourSchemaNameClass::class,
    )
)]

It will compile it down as follows

{
   "productId": 0,
   "name": "string"
}

shahrukh4 avatar Jan 23 '24 07:01 shahrukh4

Hi @shahrukh4,

thanks for your response. In the meantime i've implemented another approach.

I save all JSON-responses as files in the laravel storage folder (filename automatically generated from the request path + response code). After the openapi.json (without examples) has been generated, a laravel command parses the openapi.json, and checks if there is a corresponding JSON-response in the storage folder. This then gets added as an example for all JSON-responses available.

You only have to add the basic information in the controller.

As the responses sometimes have hundreds of lines, you don't have to put them into the controllers. Your approach would be the more elegant way, but might take more time if you have hundreds of Classes and define each property separately.

erik-re avatar Jan 26 '24 08:01 erik-re