Skip to content

Instantly share code, notes, and snippets.

@dclucas
Last active August 29, 2015 14:20
Show Gist options
  • Save dclucas/bfa45c7adb58dc0cfcf2 to your computer and use it in GitHub Desktop.
Save dclucas/bfa45c7adb58dc0cfcf2 to your computer and use it in GitHub Desktop.
Spark server with json schema validation, running on groovy
@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