Como adicionar exemplos de solicitação e resposta JSON no Swagger (OpenApi)?

Oct 05 2020

Eu tenho um endpoint de API em meu aplicativo Symfony 4, que desejo documentar com NelmioApiDocBundle e Swagger. O ponto de extremidade usa JSON como dados de solicitação e também retorna algum JSON personalizado como resposta. Como posso adicionar exemplos deles à documentação, usando anotações? Não consigo ver nenhum dos exemplos na página de documentação, apenas a descrição.

/**
 * @Route("/order/import", methods={"POST"}, name="order_import")
 * @OA\RequestBody (
 *     request="order",
 *     description="Order data in JSON format",
 *     @OA\Schema(
 *        type="object",
 *        example={"hello": "world"}
 *     )
 * )
 * @OA\Response(
 *     response=200,
 *     description="Returns the JSON data after import",
 *     @OA\Schema(
 *        type="object",
 *        example={"foo": "bar"}
 *     )
 * )
 * @OA\Tag(name="import")

Respostas

4 IhorKostrov Oct 05 2020 at 21:44

Para NelmioApiDocBundle v4, você pode fazer assim

use OpenApi\Annotations as OA;

/**
 * @OA\Parameter(
 *     name="body",
 *     in="path",
 *     required=true,
 *     @OA\JsonContent(
 *        type="object",
 *        @OA\Property(property="property1", type="number"),
 *        @OA\Property(property="property2", type="number"),
 *     ),
 * )
 *
 * @OA\Response(
 *     response=200,
 *     description="",
 *     @OA\JsonContent(
 *        type="object",
 *        @OA\Property(property="property1", type="number"),
 *        @OA\Property(property="property2", type="number"),
 *     )
 * )
 */

Para v3

use Swagger\Annotations as SWG;

/**
 * @SWG\Parameter(
 *     name="body",
 *     in="body",
 *     required=true,
 *     @SWG\Schema(
 *         @SWG\Property(property="test1", type="string"),
 *         @SWG\Property(property="test2", type="string"),
 *     ),
 * )
 *
 * @SWG\Response(
 *     description="",
 *     response=200,
 *     @SWG\Schema(
 *         @SWG\Property(property="test1", type="string"),
 *         @SWG\Property(property="test2", type="string"),
 *     ),
 * )
 */

Mas é melhor fazer isso através da anotação @Model, conforme descrito no documento se você tiver DTO ou entidade.