Skip to content

Create an API and get Swagger definition for free

License

Notifications You must be signed in to change notification settings

LookinLabs/go-fastapi

 
 

Repository files navigation

go-fastapi

Go Reference Go Report Card

go-fastapi is a library to quickly build APIs. It is inspired by Python's popular FastAPI library.

Features:

  • Auto-generated OpenAPI/Swagger schema without any markup
  • Declare handlers using types, not just Context
  • Based on gin framework

Installation: go get github.com/sashabaranov/go-fastapi

Example

package main

import (
	"github.com/gin-gonic/gin"
	"github.com/sashabaranov/go-fastapi"
)

type EchoInput struct {
	Phrase string `json:"phrase"`
}

type EchoOutput struct {
	OriginalInput EchoInput `json:"original_input"`
}

func EchoHandler(ctx *gin.Context, in EchoInput) (out EchoOutput, err error) {
	out.OriginalInput = in
	return
}

func main() {
	r := gin.Default()

	myRouter := fastapi.NewRouter()
	myRouter.AddCall("/echo", EchoHandler)

	r.POST("/api/*path", myRouter.GinHandler) // must have *path parameter
	r.Run()
}

// Try it:
//     $ curl -H "Content-Type: application/json" -X POST --data '{"phrase": "hello"}' localhost:8080/api/echo
//     {"response":{"original_input":{"phrase":"hello"}}}

OpenAPI/Swagger

To generate OpenAPI/Swagger schema:

myRouter := fastapi.NewRouter()
myRouter.AddCall("/echo", EchoHandler)

swagger := myRouter.EmitOpenAPIDefinition()
swagger.Info.Title = "My awesome API"
jsonBytes, _ := json.MarshalIndent(swagger, "", "    ")
fmt.Println(string(jsonBytes))

To serve OpenAPI/Swagger schema:

	r := gin.Default()

	// Use Router for handling API requests and generating OpenAPI definition
	myRouter := fastapi.NewRouter()
	myRouter.AddCall("/echo", EchoHandler)

	r.POST("/api/*path", myRouter.GinHandler) // must have *path parameter

	swagger := myRouter.EmitOpenAPIDefinition()
	swagger.Info.Title = "My awesome API"
	jsonBytes, _ := json.MarshalIndent(swagger, "", "    ")
	fmt.Println(string(jsonBytes))

	// Serve Swagger JSON
	r.GET("/swagger.json", func(c *gin.Context) {
		c.Data(http.StatusOK, "application/json", jsonBytes)
	})

	// Serve Swagger UI
	r.Static("/swagger-ui", "./swaggerui")

	r.Run()

You can check the example for more details about serving Swagger.

About

Create an API and get Swagger definition for free

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages

  • Go 100.0%