All Projects → cdimascio → Openapi Spring Webflux Validator

cdimascio / Openapi Spring Webflux Validator

Licence: other
🌱 A friendly kotlin library to validate API endpoints using an OpenApi 3.0 and Swagger 2.0 specification

Programming Languages

java
68154 projects - #9 most used programming language
kotlin
9241 projects

Projects that are alternatives of or similar to Openapi Spring Webflux Validator

Kotlin Openapi Spring Functional Template
🍃 Kotlin Spring 5 Webflux functional application with api request validation and interactive api doc
Stars: ✭ 159 (+137.31%)
Mutual labels:  rest, swagger, hacktoberfest, validation, spring, functional
Mockoon
Mockoon is the easiest and quickest way to run mock APIs locally. No remote deployment, no account required, open source.
Stars: ✭ 3,448 (+5046.27%)
Mutual labels:  rest, swagger, openapi, openapi3, hacktoberfest
Swagger Ui
Swagger UI is a collection of HTML, JavaScript, and CSS assets that dynamically generate beautiful documentation from a Swagger-compliant API.
Stars: ✭ 21,279 (+31659.7%)
Mutual labels:  rest, swagger, openapi, openapi3, hacktoberfest
Swagger Core
Examples and server integrations for generating the Swagger API Specification, which enables easy access to your REST API
Stars: ✭ 6,898 (+10195.52%)
Mutual labels:  rest, swagger, openapi, openapi3
Apispec
A pluggable API specification generator. Currently supports the OpenAPI Specification (f.k.a. the Swagger specification)..
Stars: ✭ 831 (+1140.3%)
Mutual labels:  swagger, openapi, openapi3, hacktoberfest
Swagger Js
Javascript library to connect to swagger-enabled APIs via browser or nodejs
Stars: ✭ 2,319 (+3361.19%)
Mutual labels:  rest, swagger, openapi3, hacktoberfest
Restful React
A consistent, declarative way of interacting with RESTful backends, featuring code-generation from Swagger and OpenAPI specs 🔥
Stars: ✭ 1,814 (+2607.46%)
Mutual labels:  rest, swagger, openapi, openapi3
Swagger Editor
Swagger Editor
Stars: ✭ 7,365 (+10892.54%)
Mutual labels:  rest, swagger, openapi3, hacktoberfest
openapi-schema-validator
OpenAPI schema validator for Python
Stars: ✭ 35 (-47.76%)
Mutual labels:  validation, swagger, openapi, openapi3
Openapi Generator
OpenAPI Generator allows generation of API client libraries (SDK generation), server stubs, documentation and configuration automatically given an OpenAPI Spec (v2, v3)
Stars: ✭ 10,634 (+15771.64%)
Mutual labels:  rest, openapi, openapi3, hacktoberfest
Dredd
Language-agnostic HTTP API Testing Tool
Stars: ✭ 3,770 (+5526.87%)
Mutual labels:  swagger, openapi, openapi3, validation
Schemathesis
A modern API testing tool for web applications built with Open API and GraphQL specifications.
Stars: ✭ 768 (+1046.27%)
Mutual labels:  swagger, openapi, openapi3, hacktoberfest
Loopback Next
LoopBack makes it easy to build modern API applications that require complex integrations.
Stars: ✭ 3,972 (+5828.36%)
Mutual labels:  rest, swagger, openapi, hacktoberfest
Goa
Design-based APIs and microservices in Go
Stars: ✭ 4,493 (+6605.97%)
Mutual labels:  rest, swagger, hacktoberfest, openapi
Gemini
Model Driven REST framework to automatically generate CRUD APIs
Stars: ✭ 138 (+105.97%)
Mutual labels:  rest, swagger, openapi, spring
openapi-schemas
JSON Schemas for every version of the OpenAPI Specification
Stars: ✭ 22 (-67.16%)
Mutual labels:  validation, swagger, openapi, openapi3
Redoc
📘 OpenAPI/Swagger-generated API Reference Documentation
Stars: ✭ 15,935 (+23683.58%)
Mutual labels:  swagger, openapi, openapi3, hacktoberfest
Kaizen Openapi Editor
Eclipse Editor for the Swagger-OpenAPI Description Language
Stars: ✭ 97 (+44.78%)
Mutual labels:  rest, swagger, openapi, openapi3
Pode
Pode is a Cross-Platform PowerShell web framework for creating REST APIs, Web Sites, and TCP/SMTP servers
Stars: ✭ 329 (+391.04%)
Mutual labels:  rest, swagger, openapi, hacktoberfest
Swagger Parser
Swagger Spec to Java POJOs
Stars: ✭ 468 (+598.51%)
Mutual labels:  rest, swagger, openapi, openapi3

openapi-spring-webflux-validator

Maven Central Download Codacy Badge All Contributors

A friendly kotlin library to validate API endpoints using an OpenApi 3 or Swagger 2 specification. Great with webflux functional. It works happily with any JVM language including Java >=8.

Supports specifications in YAML and JSON

See this complete Spring 5 Webflux example that uses openapi-spring-webflux-validator.

Prequisites

Java 8 or greater

Install

Maven

<dependency>
    <groupId>io.github.cdimascio</groupId>
    <artifactId>openapi-spring-webflux-validator</artifactId>
    <version>3.3.0</version>
</dependency>

Gradle

compile 'io.github.cdimascio:openapi-spring-webflux-validator:3.3.0'

For sbt, grape, ivy and more, see here

Usage (Kotlin)

This section and the next describe usage with Kotlin and Java respectively.

Configure (Kotlin)

This one-time configuration requires you to provide the location of the openapi/swagger specification and an optional custom error handler.

Supports JSON and YAML

import io.github.cdimascio.openapi.Validate
val validate = Validate.configure("static/api.yaml")

with custom error handler

data class MyError(val id: String, val messages: List<String>)
val validate = Validate.configure("static/api.json") { status, messages ->
   Error(status.name, messages)
}

with custom ObjectMapper factory:

val validate = Validate.configure(
   openApiSwaggerPath = "api.yaml",
   errorHandler = { status, message -> ValidationError(status.value(), message[0]) },
   objectMapperFactory = { ObjectMapper()
       .registerKotlinModule()
       .registerModule(JavaTimeModule())
       .configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false) }
)

Validate a request (Kotlin + Reactor)

You can now validate a request in a coroutine style, using the validate instance created above:

without a body

validate.request(req) {
    // Do stuff e.g. return a list of names 
    ok().body(Mono.just(listOf("carmine", "alex", "eliana")))
}

with body

validate.request(req).withBody(User::class.java) { body ->
    // Note that body is deserialized as User!
    // Now you can do stuff. 
    // For example, lets echo the request as the response 
    ok().body(Mono.just(body))
}

Validate a request (Kotlin + coroutines)

Or you can validate a request in a coroutine style, using the validate instance created above:

without a body

validate.requestAndAwait(req) {
    // Do stuff e.g. return a list of names 
    ok().bodyValueAndAwait(listOf("carmine", "alex", "eliana"))
}

with body

validate.request(req).awaitBody(User::class.java) { body: User ->
    // Note that body is deserialized as User!
    // Now you can do stuff. 
    // For example, lets echo the request as the response 
    ok().bodyValueAndAwait(body)
}

Usage (Java 8 or greater)

Configure (Java)

This one-time configuration requires you to provide the location of the openapi/swagger specification and an optional custom error handler.

import io.github.cdimascio.openapi.Validate;
Validate<ValidationError> validate = Validate.configure("static/api.json")

with custom error handler

class MyError {
    private String id;
    private  String messages;
    public MyError(String id, List<String> messages) {
        this.id = id;
        this.messages = messages;
    }
    public String getId() {
        return id;
    }
    public void setId(String id) {
        this.id = id;
    }
    public List<String> getMessages() {
        return messages;
    }
    public void setMessages(List<String> messages) {
        this.messages = messages;
    }     
}
Validate<ValidationError> validate = Validate.configure("static/api.json", (status, messages) ->
    new MyError(status.getName(), messages)
);

Validate a request (Java)

Using the validate instance created above, you can now validate a request:

without a body

ArrayList<String> users = new ArrayList<String>() {{
    add("carmine");
    add("alex");
    add("eliana");
}};

validate.request(null, () -> {
    // Do stuff e.g. return a list of user names
    ServerResponse.ok().body(fromObject(users));
});

with body

validate
    .request(null)
    .withBody(User.class, user -> 
        // Note that body is deserialized as User!
        // Now you can do stuff. 
        // For example, lets echo the request as the response
        return ServerResponse.ok().body(fromObject(user))
    );

Example Valiation Output

Let's assume a POST request to create a user requires the following request body:

{
  "firstname": "carmine",
  "lastname": "dimasico"
}

Let's now assume an API user misspells lastname as lastnam

curl -X POST http://localhost:8080/api/users -H "Content-Type: application/json" -d'{ 
  "firstname": "c", 
  "lastnam": "d" 
}'

openapi-spring-webflux-validator automatically validates the request against a Swagger spect and returns:

{
  "code": 400,
  "messages":[
	  "Object instance has properties which are not allowed by the schema: [\"lastnam\"]",
	  "Object has missing required properties ([\"lastname\"])"
  ]
} 

Woah! Cool!! :-D

Example

Let's say you have an endpoint /users that supports both GET and POST operations.

You can create those routes and validate them like so:

Create the routes in a reactive or coroutine style:

package myproject.controllers

import org.springframework.core.io.ClassPathResource
import org.springframework.http.MediaType.*
import org.springframework.web.reactive.function.server.ServerResponse.permanentRedirect
import org.springframework.web.reactive.function.server.coRouter
import org.springframework.web.reactive.function.server.plus
import org.springframework.web.reactive.function.server.router
import java.net.URI

class Routes(private val userHandler: UserHandler) {
    fun router() = router {
        "/api".nest {
            accept(APPLICATION_JSON).nest {
                POST("/users", userHandler::create)
            }
            accept(TEXT_EVENT_STREAM).nest {
                GET("/users", userHandler::findAll)
            }
        }
    } + coRouter { 
        "/coApi".nest {
            accept(APPLICATION_JSON).nest {
                POST("/users", userHandler::coCreate)
            }
            accept(TEXT_EVENT_STREAM).nest {
                GET("/users", userHandler::coFindAll)
            }
        }
    }
}
package myproject

import io.github.cdimascio.openapi.Validate
val validate = Validate.configure("static/api.yaml")

Validate with openapi-spring-webflux-validator

package myproject.controllers

import myproject.models.User
import myproject.validate
import org.springframework.web.reactive.function.server.ServerRequest
import org.springframework.web.reactive.function.server.ServerResponse
import org.springframework.web.reactive.function.server.ServerResponse.ok
import org.springframework.web.reactive.function.server.bodyValueAndAwait
import reactor.core.publisher.Flux
import reactor.core.publisher.Mono

class UserHandler {

    fun findAll(req: ServerRequest): Mono<ServerResponse> {
        return validate.request(req) {
            ok().bodyValue(listOf("carmine", "alex", "eliana"))
        }
    }

    fun create(req: ServerRequest): Mono<ServerResponse> {
        return validate.request(req).withBody(User::class.java) {
            // it is the request body deserialized as User
            ok().bodyValue(it)
        }
    }

    suspend fun coFindAll(req: ServerRequest): ServerResponse {
        return validate.requestAndAwait(req) {
            ok().bodyValueAndAwait(listOf("carmine", "alex", "eliana"))
        }
    }

    suspend fun coCreate(req: ServerRequest): ServerResponse {
        return validate.request(req).awaitBody(User::class.java) {
            // it is the request body deserialized as User
            ok().bodyValueAndAwait(it)
        }
    }
}

License

Apache 2.0

Buy Me A Coffee

Contributors ✨

Thanks goes to these wonderful people (emoji key):


Carmine DiMascio

💻 ⚠️ 📖

Krzysiek Kruczyński

💻 ⚠️ 📖

Chejerla Karthik

💻

Katie Levy

💻

Ilya Builuk

💻

Simon Zambrovski

💻 ⚠️

This project follows the all-contributors specification. Contributions of any kind welcome!

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].