Swagger Parser
Learn more about swagger parser with examples.
Join the DZone community and get the full member experience.
Join For FreeA parser is a program or library in Java that reads a file (JSON, XML, txt, etc.) and translates it to Java objects. We'll look at how to utilize Swagger Parser to extract data from a JSON file throughout this article.
About Swagger JSON File
Before starting the implementation part, let's have some basic understanding of the Swagger JSON file. It is a specification file that describes the REST APIs in accordance with the Swagger specification. The file describes details such as available endpoints, operations on each endpoint, input and output parameters for each operation, authentication methods (if present), and other information.
Sample Swagger JSON File
An overview of the fields from the sample Swagger JSON file is provided in the following table.
Field Name | Description |
---|---|
swagger |
The version of the Swagger Specification that is being used is specified. For example:
JSON
|
info | Metadata about the API is provided. For example the Application API version, title, and description.
JSON
|
basePath | The server's primary URL. The basic URL is used to reference all API endpoints. For example: / |
host | The Host of the Service. For example:
JSON
|
schemes | schemes The sort of authentication security scheme that is supported. For example:
JSON
|
paths | The relative paths to the various endpoints and operations. To create the entire URL, the path is appended to the basic URL. For example: |
description | An explanation of the operation.
JSON
|
operationId | A unique string is used to identify the operation. For example:
JSON
|
produces | A list of MIME types the operation can produce. For example:
JSON
|
consumes | A list of MIME types the operation can consume. For example:
JSON
|
parameters | A list of parameters that are applicable for the operation. For example:
JSON
|
responses | A list of possible responses is returned by executing the operation. For example, a successful response is:
JSON
|
$ref | Refer to other components in the specification, internally and externally. For example:
JSON
|
Swagger Parser Maven Dependency
We require the following dependency for Swagger Parser.
<dependency>
<groupId>io.swagger.parser.v3</groupId>
<artifactId>swagger-parser</artifactId>
<version>2.0.33</version>
</dependency>
swagger.json
With the help of Swagger Parser, the following JSON file will be used to extract data.
{
"swagger": "2.0",
"info": {
"description": "APIs to handle transactions.\n",
"version": "0.0.1",
"title": "Transaction details"
},
"host": "localhost:8080",
"basePath": "/",
"schemes": [
"http"
],
"consumes": [
"application/json"
],
"produces": [
"application/json"
],
"paths": {
"/transactions": {
"get": {
"operationId": "getAllTransactions",
"parameters": [],
"responses": {
"200": {
"description": "Get all transactions",
"schema": {
"type": "array",
"items": {
"$ref": "#/definitions/Transaction"
}
}
}
},
"x-swagger-router-controller": "Default"
},
"/transactions/{id}": {
"get": {
"operationId": "getTransactionById",
"parameters": [
{
"name": "id",
"in": "path",
"description": "Id of the transaction.",
"required": true,
"type": "string"
}
],
"responses": {
"200": {
"description": "Transaction was fetched correctly"
},
"404": {
"description": "Transaction not found"
}
},
"x-swagger-router-controller": "Default"
}
},
"post": {
"operationId": "addTransaction",
"parameters": [
{
"in": "body",
"name": "transaction",
"description": "Details of transaction we want to save",
"required": false,
"schema": {
"$ref": "#/definitions/Transaction"
}
}
],
"responses": {
"201": {
"description": "Transaction created successfully"
}
},
"x-swagger-router-controller": "Default"
},
"put": {
"operationId": "updateTransactionById",
"parameters": [
{
"name": "id",
"in": "path",
"description": "Id of the Transaction.",
"required": true,
"type": "string"
},
{
"in": "body",
"name": "transaction",
"description": "Details of the transaction we want to update",
"required": false,
"schema": {
"$ref": "#/definitions/Transaction"
}
}
],
"responses": {
"200": {
"description": "Transaction is updated successfully."
},
"500": {
"description": "Internal server error"
}
},
"x-swagger-router-controller": "Default"
},
"delete": {
"operationId": "deleteTransactionById",
"parameters": [
{
"name": "id",
"in": "path",
"description": "Id of the transaction.",
"required": true,
"type": "string"
},
{
"in": "body",
"name": "transaction",
"description": "Details of the transaction we want to remove",
"required": false,
"schema": {
"$ref": "#/definitions/Transaction"
}
}
],
"responses": {
"204": {
"description": "Transaction is deleted successfully"
},
"404": {
"description": "Transaction missing/not found"
}
},
"x-swagger-router-controller": "Default"
}
}
},
"definitions": {
"Transaction": {
"type": "object",
"properties": {
"id": {
"type": "string",
"description": "The unique ID for the transaction"
},
"text": {
"type": "string",
"description": "Transaction details"
}
}
}
}
}
Implementation
The following code demonstrates how to set up a Swagger Parser object to extract API data from a swagger.json file.
package swagger;
import java.util.Map;
import io.swagger.models.ArrayModel;
import io.swagger.models.HttpMethod;
import io.swagger.models.Model;
import io.swagger.models.Operation;
import io.swagger.models.Path;
import io.swagger.models.Response;
import io.swagger.models.Swagger;
import io.swagger.models.parameters.BodyParameter;
import io.swagger.models.parameters.Parameter;
import io.swagger.models.parameters.PathParameter;
import io.swagger.models.properties.ArrayProperty;
import io.swagger.models.properties.Property;
import io.swagger.models.properties.RefProperty;
import io.swagger.models.refs.RefFormat;
import io.swagger.parser.SwaggerParser;
public class SwaggerParserExample {
public static void main(String[] args) {
Swagger swagger = new SwaggerParser().read("swagger.json");
System.out.println("Description: " + swagger.getInfo().getDescription());
for(Map.Entry<String, Path> entry : swagger.getPaths().entrySet()) {
System.out.println(entry.getKey());
getOperationDetails(swagger, entry.getValue().getOperationMap());
}
}
private static void getOperationDetails(Swagger swagger, Map<HttpMethod, Operation> operationMap) {
for(Map.Entry<HttpMethod, Operation> op : operationMap.entrySet()) {
System.out.println("____________________________________________________\n");
System.out.println(op.getKey() + " - " + op.getValue().getOperationId());
System.out.println("Parameters ->");
for(Parameter p : op.getValue().getParameters()) {
if(p instanceof BodyParameter) {
getBodyDetails(swagger, (BodyParameter) p);
} else {
String paramType = p.getClass().getSimpleName();
if(p instanceof PathParameter) {
paramType = "path";
}
System.out.println(p.getName() + " : " + paramType);
}
}
getResponseDetails(swagger, op.getValue().getResponses());
}
}
private static void getBodyDetails(Swagger swagger, BodyParameter p) {
System.out.println("BODY: ");
RefProperty rp = new RefProperty(p.getSchema().getReference());
getReferenceDetails(swagger, rp);
}
private static void getResponseDetails(Swagger swagger, Map<String, Response> responseMap) {
System.out.println("Responses:");
System.out.println("-----------");
for(Map.Entry<String, Response> response : responseMap.entrySet()) {
System.out.println(response.getKey() + ": " + response.getValue().getDescription());
if(response.getValue().getSchema() instanceof RefProperty) {
RefProperty rp = (RefProperty)response.getValue().getSchema();
getReferenceDetails(swagger, rp);
}
if(response.getValue().getSchema() instanceof ArrayProperty) {
ArrayProperty ap = (ArrayProperty)response.getValue().getSchema();
if(ap.getItems() instanceof RefProperty) {
RefProperty rp = (RefProperty)ap.getItems();
System.out.println(rp.getSimpleRef() + "[]");
getReferenceDetails(swagger, rp);
}
}
}
}
private static void getReferenceDetails(Swagger swagger, RefProperty rp) {
if(rp.getRefFormat().equals(RefFormat.INTERNAL) &&
swagger.getDefinitions().containsKey(rp.getSimpleRef())) {
Model m = swagger.getDefinitions().get(rp.getSimpleRef());
if(m instanceof ArrayModel) {
ArrayModel arrayModel = (ArrayModel)m;
System.out.println(rp.getSimpleRef() + "[]");
if(arrayModel.getItems() instanceof RefProperty) {
RefProperty arrayModelRefProp = (RefProperty)arrayModel.getItems();
getReferenceDetails(swagger, arrayModelRefProp);
}
}
if(m.getProperties() != null) {
for (Map.Entry<String, Property> propertyEntry : m.getProperties().entrySet()) {
System.out.println(" " + propertyEntry.getKey() + " : " + propertyEntry.getValue().getType());
}
}
}
}
}
Let's launch the program now that we've finished adding the above code. If everything is in order, the parsed API information will be printed as follows.
Description: APIs to handle transactions.
/transactions
____________________________________________________
GET - getAllTransactions
Parameters ->
Responses:
-----------
200: Get all transactions
Transaction[]
id : string
text : string
____________________________________________________
PUT - updateTransactionById
Parameters ->
id : path
BODY:
id : string
text : string
Responses:
-----------
200: Transaction is updated successfully.
500: Internal server error
____________________________________________________
POST - addTransaction
Parameters ->
BODY:
id : string
text : string
Responses:
-----------
201: Transaction created successfully
____________________________________________________
DELETE - deleteTransactionById
Parameters ->
id : path
BODY:
id : string
text : string
Responses:
-----------
204: Transaction is deleted successfully
404: Transaction missing/not found
We learned how to utilize Swagger Parser to extract API specs from a JSON file in this article. We've also deciphered the structure of a JSON file field by field.
Opinions expressed by DZone contributors are their own.
Comments