Posted  by  admin

Swagger File Download Example

In this tutorial we will learn how to manage files upload and download using Spring Boot REST Services. We will also test file management with Swagger UI. In order to get started with this tutorial we suggest reading this Intro to REST Services and Swagger UI so that you can bootstrap your project quickly: Spring Boot Hello World REST Service. Swagger documents must be in either JSON format with a.json file extension, or YAML format with a.yaml or.yml file extension. IBM® Integration Bus supports version 2.0 of the Swagger specification. For information about Swagger, see Swagger.

Swagger Files (aka OpenAPI Specification) is the most popular way for documenting API specifications and Excel sheet provides an easy and simple way of writing structured data. Anybody can write data in excel sheet irrespective of their programming skills. Introducing vREST NG (An enterprise ready application for Automated API Testing), which combines the power of both to make your API Testing experience more seamless. The approach is also known as Data Driven Testing.

Data Driven testing is an approach in which test data is written separately from the test logic or script.

So, this is how the process looks like:

vREST NG uses swagger files to generate all of the test logic and sample test data CSV files. vREST NG reads test data from the CSV files and iterate over the rows available in the CSV files and run the iterations one by one. Today in this post, we will look at the following in detail:

  1. How you may generate the test cases by using the swagger files.
  2. How you may feed the test data to those generated test cases through an excel sheet.

How to perform Data Driven API Testing in vREST NG

To elaborate the process, I will take a sample test application named as contacts application which provides the CRUD APIs. I will guide you through the following steps:

  1. Setup the test application
  2. Download and Install vREST NG Application
  3. Perform Data Driven API Testing in vREST NG

Setup the Test Application:

You may skip this step if you want to follow the instructions for your own test application.

Otherwise, just download the sample Test Application from this repository link. You will also need to install the following in order to setup this sample test application:

  • NodeJS (Tested with v10.16.2)
  • MongoDB (Tested with v3.0.15)

To setup this application, simply follow the instructions mentioned in the README file of the repository.

Download and Install vREST NG Application

Now, simply download the application through vREST NG website and install it. Installation is simpler but if you need OS specific instructions, then you may follow this guide link.

After installation, start the vREST NG Application and use vREST NG Pro version when prompted in order to proceed further.

Now first setup a project by dragging any empty directory from your file system in the vREST NG workspace area. vREST NG will treat it as a project and store all the tests in that directory. For more information on setting up project, please read this guide link.

For quick start, if you don't want to follow the whole process and just want to see the end result. They may download and add this project directory in vREST NG application directly.

Performing Data Driven API Testing in vREST NG

vREST NG provides a quick 3 step process to perform data driven API Testing:

(a) Import the Swagger File

(b) Write Test Data in CSV Files

(c) [Optional] Setup Environment

Now, we will see these steps in detail:

(a) Import the Swagger File

To import the Swagger file, simply click on the Importer button available in the top left corner of the vREST NG Application.

An import dialog window will open. In this dialog window:

  1. Select 'Swagger' as Import Source
  2. Tick the option Generate Data Driven Tests. If this option is ticked then vREST NG Importer will generate the data driven test cases for each API spec available in the swagger file.
  3. Provide the swagger file. For this demonstration, we will use the swagger file from the test application repository. Download Swagger File

The dialog window will look something like this. Now, click on the Import button to proceed further.

The import process has done the following things so far:

  1. It has generated a test case for each API spec available in the Swagger or OpenAPI file. And test suites will be generated against each tag available in the swagger file.

  2. It has automatically created the sample CSV files against each test case with desired columns according to your swagger file as shown in the following image.

    We will discuss in detail on how you may fill this excel sheet later in this post.

  3. The generated CSV files are also automatically linked as shown in the following image.

    So, before every test case execution, the test case will read the data from the linked CSV file and converts it into JSON format and store it in a variable named as data. Now the test case will iterate over the data received and run the iterations. So, if you make a change in CSV file, just run the test case again. Test Case will always pick up the latest state of the CSV file. No need to import again and again.

  4. It has automatically inserted some variables in the API request params as per the API definitions available in the swagger file. These variables value will picked up from the linked CSV file automatically.

  5. It has automatically added the response validation logic as well. In the following image, status code assertion is used to validate the status code of the API response. Text Body with Default Validator assertion compares the expected response body with the actual response body. Text body with Default Schema Validator assertion validates the API response through the JSON schema.

    The expected status code will be picked up from the linked CSV file.

    And the expected response body will also be picked up from the linked CSV file.

    And the expected schema name is also picked up from the linked CSV file.

  6. It has imported all the swagger schema definitions in the Schemas section available in the Configuration tab.

    You may refer these schema definitions in the Expected Schema tab as discussed earlier. And in the CSV file, you will need to just specify the respective schema name for the test iterations in the expectedSchema column.

(b) Write Test Data in CSV Files

As we have already seen the data file generated from the import process. Let me show you the generated file again for the Create Contact API:

In this sample file, you may add test data related to various iterations for the Create Contact API. In the iterationSummary column, simply provide the meaningful summary for your iterations. This iteration summary will show up in the Results tab of the vREST NG Application. You will need to fill this test data by yourself. You may even generate this test data through any external script.

Now, let's add some test iterations in the linked CSV file.

With the above CSV file, we are checking two test conditions of our Create Contact API:

  1. When the name field is empty
  2. And when the name field length is greater than the limit of 35 characters.

In the above CSV file, we have intentionally left the expectedBody column blank. We don't need to fill this column. We can generate this column's value via the vREST NG Application itself.

Before executing the test case, we need to configure the baseURL variable of your test application in the Configuration tab like this:

In this section, you can configure your various environments like prod, dev, staging and their configurations using variables.

Now, let's execute this test in vREST NG Application. Both the iterations are failed because expected response body doesn't match with the actual response body as shown in the following image:

Now, click on button 'Copy Actual to Expected' for each iteration. vREST NG will directly copy the actual response body to expectedBody column in the linked CSV file.

Now after this operation, if you look at the CSV file again. You can see that vREST NG has filled the expectedBody column for you as shown in the following image.

Note: If you have opened this CSV file in Microsoft Excel then you will need to close the file and open it again in order to reflect the changes. But some code editors e.g. VS Code automatically detect the changes on the file system and reflect it in real time.

Now, if you execute the test again, you can see that the test iterations are now passing.

You may also see the expected vs actual response for the selected test iteration:

And you may see the execution details of the selected iteration by going to Execution Tab:

So, in this way, you may execute test iterations for an API via CSV file. Just add iterations in your CSV file and run it in the vREST NG Application directly. No need to import again and again. It all just work seamlessly. So, it increases your test efficiency and productivity drastically.

(c) [Optional] Setup Environment

For the generated steps, you may also need to set the initial application or DB state before executing your tests. So that you can perform the regressions in automated way. Some use cases of setting up initial state can be:

  1. Restoring the database state from the backups
  2. Execute an external command or script
  3. Invoke a REST API to setup the initial state

Now let's see how you may execute an external command or restore the database state from backup. Suppose for our sample test application, we already have taken a database dump and we would like to restore that dump before executing the test case. As we are using MongoDB for our sample test application, so we can use mongorestore command for our purposes.

You may specify the command as shown in the following image:

The above command will restore the database from the backup which is already there in vREST NG Project directory >> dumps folder.

Note: Make sure the mongorestore command is in your PATH, otherwise you will need to provide full path of the command.

I would like everybody to have your feedback on this approach whether you find it useful or not for your API testing needs. Do like if you find this post helpful. Feel free to contact me in case if you need any help or if you want to use the vREST NG Pro version for free.

Developing a REST API is hard.

Not only because of the effort required to design and implementation, but also the effort required for documentation so that the developers who are going to use it have a clear understanding.

Swagger is a framework that helps in the documentation of APIs.

Therefore, In this tutorial, we will see how to document and test our REST services with Swagger

What is Swagger?

If you are looking for a framework to document your API, swagger is what you are looking for.

Swagger is a framework to document and visualize Rest APIs from very different sources.

Swagger supports many frameworks including Node.js, Grails, Scala Play, Spring Boot, Symfony.

Before starting a demo, let’s me tell you what environment I’m using here to create this tutorial

Environment Details

This demo is developed using the following environment:

Hardware: i7 8650U CPU with 16 GB of RAM
Operating System: Windows 10
IDE: Eclipse
Swagger 2
and Spring Boot

Add Swagger 2 Dependencies in Spring Boot

SpringFox is a popular implementation for Swagger 2 specification. SpringFox supports both Swagger 1.2 and 2.

Let’s add Springfox dependency in pom.xml to bring it in our project.

In addition to Springfox, we need to add the dependency for swagger-ui. Let’s add springfox-swagger-ui in the pom file

Final pom.xml

Create REST APIs

Let’s create a CRUD API’s for this demo.

For this tutorial, we will expose a few REST APIs for a car showroom.

POST /api/car/add is to add the car into the car inventory database.

GET /api/car/get/{carId} is to get car details from the inventory. To retrieve car details you have to provide car id.

PUT /api/car/update/{carId}/{price:.+} is to update car’s price. To update the price of the car you have to provide id and updated price of the car.

DELETE /api/car/delete/{carId} is to delete car detail from the inventory.

Steps to create REST APIs in spring boot.

1.) Create an Entity class to define the table structure.

2.) Create a controller class to create and expose the REST apis.

3.) Create a service class that will act as a bridge between dao (repository) and controller.

4.) A repository interface that will extends Spring Data JPA’s CrudRepository interface.

EntityClass (Car.java)

Controller Class (CarController.java)

As you could see in the controller class that we have exposed few APIs for adding a car, finding a car by ID, updating a car and deleting a car by ID.

Service Class (CarService.java)

The service class acts as a bridge between the repository and the controller.

Service class gets the save request from the controller and it passes the same save the request to the repository and returns the result.

Repository Interface (CarRepository.java)

Crudrepository is is the main interface in spring data jpa that allows us to write simple crud operations without writing a single line of code

How to handle Error’s for RESTful APIs

Swagger File Download Example Online

Error Handling in REST APIs

A good REST API’s implementation should have proper error handling.

As you could see our current implementation doesn’t have code logic to handle error requests.

But still, spring boot provides the proper message when an error occurred.

Let’s hit the wrong request to see what kind of error messages we are getting now.

GET localhost:8080/api/cars/get

The response of the above request would be:

From the above response from the spring boot, it is clear that we got a 404 response that means the server unable to find the requested resource.

How to customize the error message

As we are trying to customize error response for 404 error, let’s start by writing a custom exception called ResourceNotFoundError.

As you could see ResourceNotFoundError is extending exception class and has one parameterized constructor.

Now let’s create ErrorDetail.java class and declare all the properties that we want to show in the custom error message.

As you could see above we have defined timestamp, errorMessage, and errorDetails properties which will be shown in the custom error message.

Now let’s create a main exception handler. we are annotating this class with @ControllerAdvice so that exception handling will be applied globally for all controller automatically.

In the MainExceptionHandler class, we have created two methods resourceNotFoundException and globleExcpetionHandler.

How To Download Swagger

If you notice both methods are annotated with @ExceptionHandler.

@ExceptionHandler provides the mechanism to treat exceptions that are thrown during the execution of controller operations.

Configure Swagger 2 in Spring Boot Application.

We have already added Swagger 2 dependencies earlier.

Let’s configure Swagger 2 now.

To configure Swagger 2, we will create a Docket bean in a Configuration file.

The docket is a builder pattern provided in the springfox framework that creates an interface between swagger and spring framework.

In the below class we have enabled the Swagger 2 by using @EnableSwagger2.

In addition to that, we have also provided controller base package details, API’s base URL, license details, etc.

Now let’s run the application and hit http://localhost:9000/swagger-ui.html#/ URL.

Swagger has visualized our Car Controller API’s.

Let’s add a few annotations to the controller class to make this visualization more informative.

Swagger

In the car controller and addCar method, I have added @Api, @ApiOperation, and @ApiResponse to make APIs documentation more informative.

Restart the application to see the updated result.

Conclusion

In this tutorial, we have seen that how Swagger 2 can be used to visualize REST API’s using Spring boot, Swagger 2 and SpringFox.

[Total: 0 Average: 0]

Contents

  • 6 Error Handling in REST APIs