POST request in OpenApi

Содержание
Introduction
Setup
$ref
New GET Request
Add tester with POST
Related Articles

Introduction

In this lesson you can see how to add POST request description

Setup

Using exactly same setup as in previous lesson

We will continue editing the swagger.json file. After each step is ready - will restart the http server

ref

Lets introduce powerfull feature of OpenApi - references.

It is possible to declare shemas in a reusable way and point to them with $ref syntax.

In the previous article we were describing response with just a few lines of code

"content": { "application/json": { "schema": { "type": "array", "title": "Testers",

And it was totally OK to do so since the response schema was super small - it only says that we expect an array and was not reused anywhere.

However for larger, and especially reusable schemas it is preferable to declare them separately.

Below we can find an example of declaring our response schema in a reusable way

{ "openapi": "3.1.0", "info": { "title": "QA Demo REST API", "version": "0.0.2" }, "servers": [ { "url": "http://justapi.ru" } ], "paths": { "/testers": { "get": { "summary": "Get List of Test Engineers", "operationId": "Get_List_of_Test_Engineers_get", "responses": { "200": { "description": "Successful Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/Testers" } } } } } } } }, "components": { "securitySchemes": { "basicAuth": { "type": "http", "scheme": "basic" } }, "schemas": { "Testers": { "type": "array", "title": "Testers" } } }, "security": [ { "basicAuth": [] } ] }

GET /testers/list

Since previous GET request to /testers returns always the same static list new endpoint /testers/list was created to fetch up-to-date list of testers from the Database.

Add the following code inside "paths" block just after "/testers"

"/testers/list": { "get": { "summary": "List Testers", "operationId": "list_testers_testers_list_get", "responses": { "200": { "description": "Successful Response", "content": { "application/json": { "schema": { "items": {}, "type": "array", "title": "Response List Testers Testers List Get" } } } } } } },

Restart http server and verify that now there is a second GET endpoint in Swagger UI

Using OpenApi Swagger
OpenApi
Swagger

Try out this new GET endpoint. Most likely it will return the same list as the previous one, but from the next chapter we will start updating the Database and verify updates with this new GET request so you will see that it is not static.

Add Tester

What if we know that it is possible to add new tester by sending POST request to /testers/add with tester name and favourite tool in request body.

Here is an example of adding this request to our swagger.json

Add the following code to the paths block in the same way we did with GET /testers/list

"/testers/add": { "post": { "summary": "Add Tester", "operationId": "add_tester_testers_add_post", "requestBody": { "content": { "application/json": { "schema": { "$ref": "#/components/schemas/Tester" } } }, "required": true }, "responses": { "200": { "description": "Successful Response", "content": { "application/json": { "schema": {} } } } } } }

Notice that we have something extra compared to previous get request. In the schema section there is reference to the component called Tester already in the request.

Lets create this component in the components section of our swagger.json

We can put it right after the existing Testers component

"Tester": { "properties": { "name": { "type": "string", "title": "Name" }, "tool": { "type": "string", "title": "Tool" } }, "type": "object", "required": [ "name", "tool" ], "title": "Tester" }

Restart the http server and verify that the new endpoint is visible

Using OpenApi Swagger
OpenApi
Swagger

In the Try it out section edit the request body and Execute the request

{ "name": "Alex", "tool": "Java" }

Using OpenApi Swagger
OpenApi
Swagger

Verify that the new tester is now visible in GET /testers/list reply

Using OpenApi Swagger
OpenApi
Swagger

Автор статьи: Андрей Олегович

Похожие статьи
OpenApi
Основы
Python
PowerShell
JSON

Поиск по сайту

Подпишитесь на Telegram канал @aofeed чтобы следить за выходом новых статей и обновлением старых

Перейти на канал

@aofeed

Задать вопрос в Телеграм-группе

@aofeedchat

Контакты и сотрудничество:
Рекомендую наш хостинг beget.ru
Пишите на info@urn.su если Вы:
1. Хотите написать статью для нашего сайта или перевести статью на свой родной язык.
2. Хотите разместить на сайте рекламу, подходящую по тематике.
3. Реклама на моём сайте имеет максимальный уровень цензуры. Если Вы увидели рекламный блок недопустимый для просмотра детьми школьного возраста, вызывающий шок или вводящий в заблуждение - пожалуйста свяжитесь с нами по электронной почте
4. Нашли на сайте ошибку, неточности, баг и т.д. ... .......
5. Статьи можно расшарить в соцсетях, нажав на иконку сети: