DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Related

  • How to Perform Custom Error Handling With ANTLR
  • Building Call Graphs for Code Exploration Using Tree-Sitter
  • Telemetry Pipelines Workshop: Parsing Multiple Events
  • Writing an Interpreter: Implementation

Trending

  • Understanding IEEE 802.11(Wi-Fi) Encryption and Authentication: Write Your Own Custom Packet Sniffer
  • Efficient API Communication With Spring WebClient
  • Intro to RAG: Foundations of Retrieval Augmented Generation, Part 1
  • Docker Base Images Demystified: A Practical Guide
  1. DZone
  2. Coding
  3. Languages
  4. Swagger Parser

Swagger Parser

Learn more about swagger parser with examples.

By 
Hinanaaz Sanadi user avatar
Hinanaaz Sanadi
·
Jul. 11, 22 · Tutorial
Likes (4)
Comment
Save
Tweet
Share
8.9K Views

Join the DZone community and get the full member experience.

Join For Free

A 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
 
"swagger" : "2.0"
info Metadata about the API is provided. For example the Application API version, title, and description.
JSON
 
"info": {
    "description": "APIs to handle transactions.",
    "version": "0.0.1",
    "title": "Transaction details"
  }
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
 
"host" : "localhost:8080"
schemes schemes    The sort of authentication security scheme that is supported. For example:
JSON
 
"schemes" : [ "http" ]
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: /transactions

description An explanation of the operation.
JSON
 
 "description" : "Transaction created successfully"
operationId A unique string is used to identify the operation. For example:
JSON
 
"operationId" : "operationId of the method(addTransaction)"
produces A list of MIME types the operation can produce. For example:
JSON
 
"produces" : [ "application/json", "application/xml" ]
consumes A list of MIME types the operation can consume. For example:
JSON
 
"consumes" : [ "application/json", "application/xml" ]
parameters A list of parameters that are applicable for the operation. For example:
JSON
 
"parameters": [
          {
            "in": "body",
            "name": "transaction",
            "description": "Details of transaction we want to save",
            "required": true,
            "schema": {
              "$ref": "#/definitions/Transaction"
            }
          }
        ]
responses A list of possible responses is returned by executing the operation. For example, a successful response is:
JSON
 
"responses": {
          "201": {
            "description": "Transaction created successfully"
          }
        }
$ref Refer to other components in the specification, internally and externally.
For example:
JSON
 
"$ref" : "#/definitions/TransactionsFromThirdParty"

Swagger Parser Maven Dependency

We require the following dependency for Swagger Parser.

HXML
 
<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.

JSON
 
{
  "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.

Java
 
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.

Shell
 
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.

Parser (programming language)

Opinions expressed by DZone contributors are their own.

Related

  • How to Perform Custom Error Handling With ANTLR
  • Building Call Graphs for Code Exploration Using Tree-Sitter
  • Telemetry Pipelines Workshop: Parsing Multiple Events
  • Writing an Interpreter: Implementation

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!