Friday, 15 April 2022

Spring: openAPI: Define API server host and base url

Using ‘servers’ attribute of @OpenAPIDefinition annotation, we can define API server host and base url.

 

Example

@Configuration
@OpenAPIDefinition(
        info = @Info(
                title = "Demo Appication",
                version = "1.0.0",
                description = "Demo Appication",
                contact = @Contact(name = "Java tutorial team", email = "test@test.com")
        ),
        servers = {
        		@Server(url = "http://localhost:8080", description = "local server"),
        		@Server(url = "https://chat.dev.com", description = "Development server"),
                @Server(url = "https://chat.qa.com", description = "QA server"),
                @Server(url = "https://chat.prod.com", description = "prod server")
                },
        security = {
                @SecurityRequirement(name = "serverName"),
                @SecurityRequirement(name ="key")
        }
)
@SecuritySchemes(value = {
        @SecurityScheme(name = "serverName",
                type = SecuritySchemeType.APIKEY,
                in = SecuritySchemeIn.HEADER,
                paramName = "server.name",
                description = "server name to authenticate"),
        @SecurityScheme(name = "key",
                type = SecuritySchemeType.APIKEY,
                in = SecuritySchemeIn.HEADER,
                paramName = "server.key",
                description = "server key to authenticate")
})
public class SwaggerConfig {

}

 

Find the below working application.

 

Step 1: Create new maven project ‘openapi-define-server’.

 

Step 2: Update pom.xml with maven dependencies.

 

pom.xml

 

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
        <modelVersion>4.0.0</modelVersion>
        <groupId>com.sample.app</groupId>
        <artifactId>openapi-define-server</artifactId>
        <version>1</version>

        <parent>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-parent</artifactId>
                <version>2.6.4</version>
        </parent>


        <properties>
                <java.version>1.8</java.version>
                <maven.compiler.source>${java.version}</maven.compiler.source>
                <maven.compiler.target>${java.version}</maven.compiler.target>
                <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
                <project.report.outputEncoding>UTF-8</project.report.outputEncoding>
        </properties>
        
        <dependencies>
                <dependency>
                        <groupId>org.springframework.boot</groupId>
                        <artifactId>spring-boot-starter-web</artifactId>
                </dependency>


                <dependency>
                        <groupId>org.springdoc</groupId>
                        <artifactId>springdoc-openapi-ui</artifactId>
                        <version>1.6.6</version>
                </dependency>


        </dependencies>
</project>

 

Step 3: Define SwaggerConfig class.

 

SwaggerConfig.java

 

package com.sample.app.config;

import org.springframework.context.annotation.Configuration;

import io.swagger.v3.oas.annotations.OpenAPIDefinition;
import io.swagger.v3.oas.annotations.enums.SecuritySchemeIn;
import io.swagger.v3.oas.annotations.enums.SecuritySchemeType;
import io.swagger.v3.oas.annotations.info.Contact;
import io.swagger.v3.oas.annotations.info.Info;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import io.swagger.v3.oas.annotations.security.SecurityScheme;
import io.swagger.v3.oas.annotations.security.SecuritySchemes;
import io.swagger.v3.oas.annotations.servers.Server;

@Configuration
@OpenAPIDefinition(
        info = @Info(
                title = "Demo Appication",
                version = "1.0.0",
                description = "Demo Appication",
                contact = @Contact(name = "Java tutorial team", email = "test@test.com")
        ),
        servers = {
                        @Server(url = "http://localhost:8080", description = "local server"),
                        @Server(url = "https://chat.dev.com", description = "Development server"),
                @Server(url = "https://chat.qa.com", description = "QA server"),
                @Server(url = "https://chat.prod.com", description = "prod server")
                },
        security = {
                @SecurityRequirement(name = "serverName"),
                @SecurityRequirement(name ="key")
        }
)
@SecuritySchemes(value = {
        @SecurityScheme(name = "serverName",
                type = SecuritySchemeType.APIKEY,
                in = SecuritySchemeIn.HEADER,
                paramName = "server.name",
                description = "server name to authenticate"),
        @SecurityScheme(name = "key",
                type = SecuritySchemeType.APIKEY,
                in = SecuritySchemeIn.HEADER,
                paramName = "server.key",
                description = "server key to authenticate")
})
public class SwaggerConfig {

}

 

Step 4: Define UserController class.

 

UserController.java

 

package com.sample.app.controller;

import java.util.HashMap;
import java.util.Map;

import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.enums.ParameterIn;

@RestController
@RequestMapping(value = "/api/v1/users")
@CrossOrigin("*")
public class UserController {

        @GetMapping("/by-name")
        public ResponseEntity<Map<String, Object>> infoByName(
                        @Parameter(name = "firstName", in = ParameterIn.QUERY, description = "firstName ex: krishna", required = true) @RequestParam(name = "firstName", required = false) String firstName,
                        @Parameter(name = "lastName", in = ParameterIn.QUERY, description = "lastName ex: krishna", required = true) @RequestParam(name = "lastName", required = false) String lastName) {

                Map<String, Object> myDetails = new HashMap<>();

                if (firstName != null) {
                        myDetails.put("firstName", firstName);
                }

                if (lastName != null) {
                        myDetails.put("lastName", lastName);
                }

                return ResponseEntity.ok(myDetails);

        }

}

 

Step 5: Define main application class.

 

App.java

 

package com.sample.app;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class App {
        public static void main(String[] args) {

                SpringApplication.run(App.class, args);

        }
}

 

Total project structure looks like below.

 


 

Run App.java.

 

Open the url ‘http://localhost:8080/swagger-ui/index.html’ in browser.



Click on Authorize button and provide api keys. Select the server that you want to connect to from the Servers drop down.

 


 

Execute the api ‘GET /api/v1/users/by-name’, you will observe that the request hit the respective server.

 

You can download the complete working application from this link.


Previous                                                    Next                                                    Home

No comments:

Post a Comment