How to add JSON request and response examples in Swagger (OpenApi)?

9.8k views Asked by At

I have an API endpoint in my Symfony 4 application, that I want to document with NelmioApiDocBundle and Swagger. The endpoint takes JSON as a request data and also returns some custom JSON as the response. How can I add examples of them to the documentation, using annotations? I can't see any of the examples on the documentation page, only the 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")
1

There are 1 answers

1
Ihor Kostrov On BEST ANSWER

For NelmioApiDocBundle v4 you can do like this

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

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

But better to do it via @Model annotation, as described in the doc if you have DTO or entity.