Comment ajouter des exemples de requête et de réponse JSON dans Swagger (OpenApi)?

Oct 05 2020

J'ai un point de terminaison API dans mon application Symfony 4, que je souhaite documenter avec NelmioApiDocBundle et Swagger. Le point de terminaison prend JSON en tant que données de demande et renvoie également un JSON personnalisé en tant que réponse. Comment puis-je en ajouter des exemples à la documentation, à l'aide d'annotations? Je ne vois aucun des exemples sur la page de documentation, seulement la description.

/**
 * @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")

Réponses

4 IhorKostrov Oct 05 2020 at 21:44

Pour NelmioApiDocBundle v4, vous pouvez faire comme ceci

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"),
 *     )
 * )
 */

Pour la 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"),
 *     ),
 * )
 */

Mais mieux vaut le faire via l'annotation @Model, comme décrit dans la doc si vous avez un DTO ou une entité.