OpenAPI spec validation in Golang

I use https://github.com/go-openapi quite a lot and find that packages very useful to work with OpenAPI spec, validations and other related stuff.

Validate the spec itself

Take a look at the following code:

document, err = loads.Spec(fpath)
if err != nil {
    return nil, errors.Wrap(err, "Failed to load spec")
}

document, err = document.Expanded(&spec.ExpandOptions{RelativeBase: fpath})
if err != nil {
    return nil, errors.Wrap(err, "Failed to expand spec")
}

if err := validate.Spec(document, strfmt.Default); err != nil {
    return nil, errors.Wrap(err, "Spec is invalid")
}

First of all, it loads spec. Then it expands all references ($ref-s) in that spec. After that it validates the spec itself.

Validate by spec

So the spec itself is correct. Now we want to validate, for example, a request body by that spec.

// sch here is the schema object that can be extracted from
// the spec that you created above.

// data is just an interface{} that represents your data
// structure that you need to validate. data is a struct
// you decoded a json body into like json.Unmarshal(b, &data)

err := validate.AgainstSchema(sch, data, strfmt.Default)
ve, ok := err.(*errors.CompositeError)

// now you can extract errors from ve.Errors

I've build some wrappers around it for easy request validations, for example:

// op here is the OpenAPI operation object that can also be extracted
// from the spec loaded above.
if errs := validate.Body(op.Parameters, body); len(errs) > 0 {
    // work with errs
}

Disclaimer: Some links above lead to the repository oas2 where I am an author and a maintainer. That repository is build on top of go-openapi where I am not the author.