POST API with request body as JSON in Swagger
This article mainly discusses on “message body does not match the declared format” issue encountered while integrating Swagger for POST requests with a Ruby on Rails repository and how to resolve it.
By Kripa K — “An Inquisitive learner”
The most recent versions of Ruby and Rails are being used to set up a Ruby on Rails repository. Swagger has been incorporated as an API documentation testing tool for the Rest APIs. Version details of ruby, rails, and swagger are provided below.
Ruby Version — 3.2.0
Rails Version — 188.8.131.52
Swagger UI Package: Version 4.15.5
Download the latest swagger UI package into your local machine and unzip it. To integrate swagger UI, copy the contents within the dist folder of Swagger UI into the public/api/docs folder of the rails repository.
To make swagger work, we have to add this one line to Api::V1::Base modulehttps://gist.github.com/kripz97/9f6cba36ed39e27767168b767a2a3975
Restart server and check http://localhost:3000/api/docs/index.html. Swagger should be enabled.
The request Content-Type was always set to application/json in the new Swagger UI, which was perfect for GET requests with parameters. It is different when it comes to POST requests. Though Content-Type is set as application/json, parameter content type is always set as form data.
Form parameters are used to describe the payload of requests whose content type is application/x-www-form-urlencoded (used to POST primitive values and arrays of primitive values) or multipart/form-data (used to upload files or a combination of files and primitive data). But in the new swagger request content type is always set as “application/json”
Even though form data is sent as param type, content-type is set as “application/json” which creates a conflict in the request header and parameter content type and throws an error message to send valid application/json in the request’s body.
We are aware that swagger’s default content type setting is application/json. Hence the request body for POST requests must be sent as JSON or XML data. The request body is referred to as body parameters in swagger. So param type should be set as body within swagger documentation for each parameter.https://gist.github.com/kripz97/5695af3619022b8631782a5c5a0f56de
Here the parameter content type is now set as application/json and parameters are added in JSON format. Now the request is executed successfully.
Thus the header content type and parameter type conflict are now resolved and we can test the POST API requests with swagger toolkit.
We at CaratLane are solving some of the most intriguing challenges to make our mark in the relatively uncharted omnichannel jewellery industry. If you are interested in tackling such obstacles, feel free to drop your updated resume/CV to firstname.lastname@example.org