Come aggiungere esempi di richieste e risposte JSON in Swagger (OpenApi)?
Oct 05 2020
Ho un endpoint API nella mia applicazione Symfony 4, che voglio documentare con NelmioApiDocBundle e Swagger. L'endpoint accetta JSON come dati di richiesta e restituisce anche alcuni JSON personalizzati come risposta. Come posso aggiungerne esempi alla documentazione, utilizzando annotazioni? Non riesco a vedere nessuno degli esempi nella pagina della documentazione, solo la descrizione.
/**
* @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")
Risposte
4 IhorKostrov Oct 05 2020 at 21:44
Per NelmioApiDocBundle v4 puoi fare così
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"),
* )
* )
*/
Per 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"),
* ),
* )
*/
Ma meglio farlo tramite l'annotazione @Model, come descritto nel documento se hai DTO o entità.