Code Monkey home page Code Monkey logo

gswagger's Introduction

Build Status Coverage Status Go Report Card GoDoc

gswagger

Generate an openapi spec dynamically based on the types used to handle request and response.

It works with any router, it is simple to add support to your router implementing the apirouter interface.

The routers supported out of the box are:

This lib uses kin-openapi to automatically generate and serve a swagger file.

To convert struct to schemas, we use jsonschema library.
The struct must contains the appropriate struct tags to be inserted in json schema to generate the schema dynamically.
It is always possible to add a totally custom swagger schema using kin-openapi.

Install

To use it, install with

go get github.com/davidebianchi/gswagger

Usage

An example usage of this lib with gorilla mux:

context := context.Background()
muxRouter := mux.NewRouter()

router, _ := swagger.NewRouter(gorilla.NewRouter(muxRouter), swagger.Options{
  Context: context,
  Openapi: &openapi3.T{
    Info: &openapi3.Info{
      Title:   "my title",
      Version: "1.0.0",
    },
  },
})

okHandler := func(w http.ResponseWriter, req *http.Request) {
  w.WriteHeader(http.StatusOK)
  w.Write([]byte("OK"))
}

type User struct {
  Name        string   `json:"name" jsonschema:"title=The user name,required" jsonschema_extras:"example=Jane"`
  PhoneNumber int      `json:"phone" jsonschema:"title=mobile number of user"`
  Groups      []string `json:"groups,omitempty" jsonschema:"title=groups of the user,default=users"`
  Address     string   `json:"address" jsonschema:"title=user address"`
}
type errorResponse struct {
  Message string `json:"message"`
}

router.AddRoute(http.MethodPost, "/users", okHandler, swagger.Definitions{
  RequestBody: &swagger.ContentValue{
    Content: swagger.Content{
      "application/json": {Value: User{}},
    },
  },
  Responses: map[int]swagger.ContentValue{
    201: {
      Content: swagger.Content{
        "text/html": {Value: ""},
      },
    },
    401: {
      Content: swagger.Content{
        "application/json": {Value: &errorResponse{}},
      },
      Description: "invalid request",
    },
  },
})

router.AddRoute(http.MethodGet, "/users", okHandler, swagger.Definitions{
  Responses: map[int]swagger.ContentValue{
    200: {
      Content: swagger.Content{
        "application/json": {Value: &[]User{}},
      },
    },
  },
})

carSchema := openapi3.NewObjectSchema().WithProperties(map[string]*openapi3.Schema{
  "foo": openapi3.NewStringSchema(),
  "bar": openapi3.NewIntegerSchema().WithMax(15).WithMin(5),
})
requestBody := openapi3.NewRequestBody().WithJSONSchema(carSchema)
operation := swagger.NewOperation()
operation.AddRequestBody(requestBody)

router.AddRawRoute(http.MethodPost, "/cars", okHandler, operation)

router.GenerateAndExposeOpenapi()

This configuration will output the schema shown here.

Auto generated path params schema

The path params, if not set in schema, are auto generated from the path. The format of the path parameters depends on the router library you are using, as explained below.

Gorilla Mux

Gorilla Mux supports the path parameters as {someParam}, for example as in /users/{userId}.

Here is the example test.

The generated oas schema will contains userId, carId and driverId as path params set to string. If only one params is set, you must specify manually all the path params.

The generated OAS for this test case is visible here.

Fiber

Fiber supports the path parameters as :someParam, for example as in /users/:userId.

Here is the example test

SubRouter

It is possible to create a new sub router from the swagger.Router. It is possible to add a prefix to all the routes created under the specific router (instead of use the router specific methods, if given, or repeat the prefix for every route).

It could also be useful if you need a sub router to create a group of APIs which use the same middleware (for example,this could be achieved by the SubRouter features of gorilla mux, for example).

To see the SubRouter example, please see the integration test of one of the supported routers.

FAQ

  1. How to add format binary? Formats date-time, email, hostname, ipv4, ipv6, uri could be added with tag jsonschema. Others format could be added with tag jsonschema_extra. Not all the formats are supported (see discovered unsupported formats here).

  2. How to add a swagger with allOf? You can create manually a swagger with allOf using the AddRawRoute method.

  3. How to add a swagger with anyOf? You can create manually a swagger with anyOf using the AddRawRoute method.

  4. How to add a swagger with oneOf? You can create manually a swagger with oneOf using the AddRawRoute method, or use the jsonschema struct tag.

Discovered unsupported schema features

Formats:

Versioning

We use SemVer for versioning. For the versions available, see the tags on this repository.

gswagger's People

Contributors

danibix95 avatar davidebianchi avatar dependabot-preview[bot] avatar dependabot[bot] avatar filipporezzonico avatar fredmaggiowski avatar malta895 avatar mia-deltat1995 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

gswagger's Issues

Fiber path parameter syntax is not supported

When gswagger is used with fiber routes it fails to validate path parameters. The reason seems to be that the expected syntax for path parameters is {parameter} while fiber uses the colon syntax :parameter.

Automatically set params in swagger

If a path contains some params, if not declared the swagger is not valid.

A possible solution to avoid this, is to set the path parameters by default in schema (and it should be possible to overwrite it from the swagger definition)

Road to initial release

Tasks to make before the initial release:

  • rename New function to NewRouter
  • verify oneOf support
  • verify allOf support
  • verify anyOf support
  • add constants to handle common content-type, like application/json
  • add yaml endpoint for openapi documentation
  • custom documentation path

How to use with Fiber

Hello @davidebianchi , I'm trying to use this with Fiber but the example is not very clear. Assuming my Fiber main is as follow:

func main() {
  app := fiber.New()

  api := app.Group("/api", middleware) // /api

  v1 := api.Group("/v1", middleware)   // /api/v1
  v1.Get("/list", handler)             // /api/v1/list
  v1.Get("/user", handler)             // /api/v1/user

  v2 := api.Group("/v2", middleware)   // /api/v2
  v2.Get("/list", handler)             // /api/v2/list
  v2.Get("/user", handler)             // /api/v2/user

  log.Fatal(app.Listen(":3000"))
}

How do you add gswagger support?

Add ref to Responses

Hi @davidebianchi,

Is there a way to add a reference to component/definition to a response (gswagger.Definitions)? Right now seems it only accepts pure schemas but not refs to the schemas.

Thank you!

Add a function to integrate json request/response

If the content-type is defined as application/json, we could validate the request upon the given schema, unmarshal the request and marshal the response and add the correct response content-type.

In this way, the creation of json handler will be easier.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.