Last active
August 29, 2015 14:20
-
-
Save dclucas/bfa45c7adb58dc0cfcf2 to your computer and use it in GitHub Desktop.
Spark server with json schema validation, running on groovy
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@Grab('com.github.fge:json-schema-validator:2.2.6') | |
@Grab('com.sparkjava:spark-core:2.1') | |
import spark.* | |
import static spark.Spark.* | |
import com.github.fge.jackson.JsonLoader | |
import com.github.fge.jsonschema.main.JsonSchemaFactory | |
def factory = JsonSchemaFactory.byDefault() | |
def jsonContents = JsonLoader.fromString('{"properties":{"id":{"type":"string"},"title":{"type":"string"}},"required":["id","title"]}') | |
def schema = factory.getJsonSchema(jsonContents) | |
println 'Starting server' | |
post '/posts', { req, res -> 'Hello World' } | |
before '/posts', { req, res -> | |
println req.body() | |
def r = schema.validate(JsonLoader.fromString(req.body())) | |
if (! r.isSuccess()) { | |
halt(400, r.collect({ it.message}).join(',')) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment