Skip to content

Instantly share code, notes, and snippets.

@slinkydeveloper
Last active February 25, 2020 15:48
Show Gist options
  • Save slinkydeveloper/bdf5929c2506988d78fc08205089409a to your computer and use it in GitHub Desktop.
Save slinkydeveloper/bdf5929c2506988d78fc08205089409a to your computer and use it in GitHub Desktop.
vertx-OpenAPI3-example
import io.vertx.core.AbstractVerticle;
import io.vertx.core.Vertx;
import io.vertx.core.http.HttpServer;
import io.vertx.core.http.HttpMethod;
import io.vertx.core.http.HttpServerOptions;
import io.vertx.core.json.JsonObject;
import io.vertx.core.logging.Logger;
import io.vertx.core.logging.LoggerFactory;
import io.vertx.ext.web.RequestParameters;
import io.vertx.ext.web.RequestParameter;
import io.vertx.ext.web.Router;
import io.vertx.ext.web.designdriven.OpenAPI3RouterFactory;
import io.vertx.ext.web.validation.ValidationException;
import io.vertx.ext.web.RoutingContext;
public class MainVerticle extends AbstractVerticle {
HttpServer server;
Logger logger = LoggerFactory.getLogger("MainVerticle");
public void start() {
// Load the api spec. This operation is asynchronous
OpenAPI3RouterFactory.createRouterFactoryFromFile(this.vertx, "src/main/resources/petstore.yaml", openAPI3RouterFactoryAsyncResult -> {
if (openAPI3RouterFactoryAsyncResult.succeeded()) {
// Spec loaded with success
OpenAPI3RouterFactory routerFactory = openAPI3RouterFactoryAsyncResult.result();
// Add an handler with operationId
routerFactory.addHandlerByOperationId("listPets", routingContext -> {
// Handle listPets operation
RequestParameters params = routingContext.get("parsedParameters");
RequestParameter limitParameter = params.queryParameter( /* Parameter name */ "limit");
if (limitParameter != null && !limitParameter.isNull()) {
// limit parameter exists, use it!
Integer limit = limitParameter.getInteger();
} else {
// limit parameter doesn't exist (it's not required)
}
routingContext.response().setStatusMessage("Called listPets").end();
}, routingContext -> {
// This is the failure handler
Throwable failure = routingContext.failure();
if (failure instanceof ValidationException)
// Handle Validation Exception
routingContext.response().setStatusCode(400).setStatusMessage("ValidationError").end(failure.getMessage());
});
// Add an handler with a combination of HttpMethod and path
routerFactory.addHandler(HttpMethod.POST, "/pets", routingContext -> {
// Extract request body and use it
RequestParameters params = routingContext.get("parsedParameters");
JsonObject pet = params.body().getJsonObject();
routingContext.response()
.putHeader("content-type", "application/json; charset=utf-8")
.end(pet.encodePrettily());
}, routingContext -> {
Throwable failure = routingContext.failure();
if (failure instanceof ValidationException)
// Handle Validation Exception
routingContext.response().setStatusCode(400).setStatusMessage("ValidationError").end(failure.getMessage());
});
// Add a security handler
routerFactory.addSecurityHandler("api_key", routingContext -> {
// Handle security here and then call next()
routingContext.next();
});
// Before router creation you can enable or disable mounting a default failure handler for ValidationException
routerFactory.enableValidationFailureHandler(false);
// Now you have to generate the router
Router router = routerFactory.getRouter();
// Now you can use your Router instance
HttpServer server = vertx.createHttpServer(new HttpServerOptions().setPort(8080).setHost("localhost"));
server.requestHandler(router::accept).listen();
} else {
// Something went wrong during router factory initialization
Throwable exception = openAPI3RouterFactoryAsyncResult.cause();
logger.error("Ops!", exception);
}
});
logger.info("Server started!");
}
public void stop() { this.server.close(); }
public static void main(String[] args) {
Vertx vertx = Vertx.vertx();
vertx.deployVerticle(new MainVerticle());
}
}
openapi: 3.0.0
info:
version: 1.0.0
title: Swagger Petstore
license:
name: MIT
servers:
- url: http://petstore.swagger.io/v1
paths:
/pets:
get:
summary: List all pets
operationId: listPets
tags:
- pets
parameters:
- name: limit
in: query
description: How many items to return at one time (max 100)
required: false
schema:
type: integer
format: int32
responses:
200:
description: An paged array of pets
headers:
x-next:
description: A link to the next page of responses
schema:
type: string
content:
application/json:
schema:
$ref: "#/components/schemas/Pets"
default:
description: unexpected error
content:
application/json:
schema:
$ref: "#/components/schemas/Error"
post:
summary: Create a pet
operationId: createPets
tags:
- pets
responses:
201:
description: Null response
default:
description: unexpected error
content:
application/json:
schema:
$ref: "#/components/schemas/Error"
/pets/{petId}:
get:
summary: Info for a specific pet
operationId: showPetById
security:
- api_key: []
tags:
- pets
parameters:
- name: petId
in: path
required: true
description: The id of the pet to retrieve
schema:
type: string
responses:
200:
description: Expected response to a valid request
content:
application/json:
schema:
$ref: "#/components/schemas/Pets"
default:
description: unexpected error
content:
application/json:
schema:
$ref: "#/components/schemas/Error"
components:
schemas:
Pet:
type: object
required:
- id
- name
properties:
id:
type: integer
format: int64
name:
type: string
tag:
type: string
Pets:
type: array
items:
$ref: "#/components/schemas/Pet"
Error:
type: object
required:
- code
- message
properties:
code:
type: integer
format: int32
message:
type: string
securitySchemes:
api_key:
type: apiKey
name: api_key
in: header
openIdConnectUrl: "http://www.example.com"
<?xml version="1.0" encoding="UTF-8"?>
<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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>project-id</groupId>
<artifactId>my-awesome-project-with-openapi3-vertx</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>jar</packaging>
<properties>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
</properties>
<repositories>
<repository>
<id>jitpack.io</id>
<url>https://jitpack.io</url>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>com.github.slinkydeveloper</groupId>
<artifactId>vertx-web</artifactId>
<version>89d6254d50</version>
</dependency>
</dependencies>
</project>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment