Code Monkey home page Code Monkey logo

rest's Introduction

REST

Document a REST API with an OpenAPI 3.0 specification.

  • Code, not configuration.
  • No magic comments, tags, or decorators.
  • Use with or without a Go web framework.
  • Populates schema automatically using reflection.

Why would I want to use this?

  • Add OpenAPI documentation to an API.
    • Create a swagger.json or swagger.yaml file.
  • Serve the Swagger UI to customers.

Examples

See the ./examples directory for complete examples.

Create an OpenAPI 3.0 (swagger) file

// Configure the models.
api := rest.NewAPI("messages")
api.StripPkgPaths = []string{"github.com/a-h/rest/example", "github.com/a-h/respond"}

api.RegisterModel(rest.ModelOf[respond.Error](), rest.WithDescription("Standard JSON error"), func(s *openapi3.Schema) {
  status := s.Properties["statusCode"]
  status.Value.WithMin(100).WithMax(600)
})

api.Get("/topic/{id}").
  HasPathParameter("id", rest.PathParam{
    Description: "id of the topic",
    Regexp:      `\d+`,
  }).
  HasResponseModel(http.StatusOK, rest.ModelOf[models.Topic]()).
  HasResponseModel(http.StatusInternalServerError, rest.ModelOf[respond.Error]())

// Create the specification.
spec, err := api.Spec()
if err != nil {
  log.Fatalf("failed to create spec: %v", err)
}

// Write to stdout.
enc := json.NewEncoder(os.Stdout)
enc.SetIndent("", " ")
enc.Encode(spec)

Serve API documentation alongside your API

// Create routes.
router := http.NewServeMux()
router.Handle("/topics", &get.Handler{})
router.Handle("/topic", &post.Handler{})

api := rest.NewAPI("messages")
api.StripPkgPaths = []string{"github.com/a-h/rest/example", "github.com/a-h/respond"}

// Register the error type with customisations.
api.RegisterModel(rest.ModelOf[respond.Error](), rest.WithDescription("Standard JSON error"), func(s *openapi3.Schema) {
  status := s.Properties["statusCode"]
  status.Value.WithMin(100).WithMax(600)
})

api.Get("/topics").
  HasResponseModel(http.StatusOK, rest.ModelOf[get.TopicsGetResponse]()).
  HasResponseModel(http.StatusInternalServerError, rest.ModelOf[respond.Error]())

api.Post("/topic").
  HasRequestModel(rest.ModelOf[post.TopicPostRequest]()).
  HasResponseModel(http.StatusOK, rest.ModelOf[post.TopicPostResponse]()).
  HasResponseModel(http.StatusInternalServerError, rest.ModelOf[respond.Error]())

// Create the spec.
spec, err := api.Spec()
if err != nil {
  log.Fatalf("failed to create spec: %v", err)
}

// Apply any global customisation.
spec.Info.Version = "v1.0.0."
spec.Info.Description = "Messages API"

// Attach the Swagger UI handler to your router.
ui, err := swaggerui.New(spec)
if err != nil {
  log.Fatalf("failed to create swagger UI handler: %v", err)
}
router.Handle("/swagger-ui", ui)
router.Handle("/swagger-ui/", ui)

// And start listening.
fmt.Println("Listening on :8080...")
fmt.Println("Visit http://localhost:8080/swagger-ui to see API definitions")
fmt.Println("Listening on :8080...")
http.ListenAndServe(":8080", router)

Tasks

test

go test ./...

run-example

Dir: ./example/stdlib

go run main.go

rest's People

Contributors

a-h avatar dandycodes avatar joerdav avatar laurabirchiw avatar richardinnocent avatar stianhj avatar

Stargazers

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

Watchers

 avatar  avatar

rest's Issues

feature request: add support for authentication

To add JWT authentication to an API, requires this... as per https://swagger.io/docs/specification/authentication/bearer-authentication/

	spec, err := api.Spec()
	if err != nil {
		log.Error("failed to create spec", slog.Any("error", err))
		os.Exit(1)
	}

	spec.Components.SecuritySchemes = map[string]*openapi3.SecuritySchemeRef{
		"bearerAuth": {
			Value: openapi3.NewJWTSecurityScheme(),
		},
	}

	securitySchemeToScopes := openapi3.NewSecurityRequirement()
	securitySchemeToScopes.Authenticate("bearerAuth")
	spec.Security = *openapi3.NewSecurityRequirements().
		With(securitySchemeToScopes)

Since it's so common, maybe it would be better as:

        api.SetAuth(rest.JWTBearerAuth())

	spec, err := api.Spec()
	if err != nil {
		log.Error("failed to create spec", slog.Any("error", err))
		os.Exit(1)
	}

Not sure about how the API would look to support mixed authentication (some handlers authenticated, some open). Maybe that would be out of scope.

Persist deprecation of fields to TS models

Background

If I deprecate a field in Go, I would like the field to marked as deprecated in the OpenAPI specification. This will allow users of my OpenAPI spec to be aware of which fields they should avoid.

Scenario

I have the following struct defined in Go:

type ExampleStruct struct {
    // NewField is the field that should be used.
    NewField string

    // OldField is the field that used to be used.
    // Deprecated: Use NewField instead.
    OldField string
}

Expected

This would create a model in the OpenAPI specification such as:

ExampleStruct:
  type: object
  properties:
    NewField:
      description: NewField is the field that should be used.
      type: string
    OldField:
      deprecated: true
      description: |-
        OldField is the field that used to be used.
        Deprecated: Use NewField instead.
      type: string
  required:
  - NewField
  - OldField

Note that OldField is marked as deprecated.

Actual

The model is created without any deprecation flag i.e.:

ExampleStruct:
  type: object
  properties:
    NewField:
      description: NewField is the field that should be used.
      type: string
    OldField:
      description: |-
        OldField is the field that used to be used.
        Deprecated: Use NewField instead.
      type: string
  required:
  - NewField
  - OldField

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.