Coder Social home page Coder Social logo

goapidoc's Introduction

goapidoc

Build Status codecov Go Report Card License Release

  • A golang library for generating api document, including swagger2 and apib.

Function

  • Support api, routes and definitions information
  • Support generic definition type
  • Support most of the functions for swagger 2
  • Support basic functions for API Blueprint 1A

Usage

package main

import (
	. "github.com/Aoi-hosizora/goapidoc"
)

func main() {
	SetDocument("localhost:60001", "/",
		NewInfo("Demo api", "This is a demo api only for testing goapidoc.", "1.0.0").
			License(NewLicense("MIT", "")).
			Contact(NewContact("", "https://github.com/Aoi-hosizora", "")),
	)

	SetOption(NewOption().
		Schemes("http").
		Tags(
			NewTag("Authorization", "auth-controller"),
			NewTag("User", "user-controller"),
		).
		Securities(
			NewApiKeySecurity("jwt", HEADER, "Authorization"),
		).
		GlobalParams(
			NewQueryParam("force_refresh", "boolean", false, "force refresh flag").Default(false),
			NewHeaderParam("X-Special-Flag", "string", false, "a special flag in header").Example("token-xxx"),
		),
	)

	AddOperations(
		NewPostOperation("/auth/register", "Sign up").
			Tags("Authorization").
			Params(
				NewBodyParam("param", "RegisterParam", true, "register param"),
			).
			Responses(
				NewResponse(200, "Result"),
			),

		NewPostOperation("/auth/login", "Sign in").
			Tags("Authorization").
			Params(
				NewBodyParam("param", "LoginParam", true, "login param"),
			).
			Responses(
				NewResponse(200, "_Result<LoginDto>"),
			),

		NewGetOperation("/auth/me", "Get the authorized user").
			Tags("Authorization").
			Securities("jwt").
			Responses(
				NewResponse(200, "_Result<UserDto>"),
			),

		NewDeleteOperation("/auth/logout", "Sign out").
			Tags("Authorization").
			Securities("jwt").
			Responses(
				NewResponse(200, "Result"),
			),
	)

	AddOperations(
		NewGetOperation("/user", "Query all users").
			Tags("User").
			Securities("jwt").
			Params(
				NewQueryParam("page", "integer#int32", false, "query page").Default(1),
				NewQueryParam("limit", "integer#int32", false, "page size").Default(20),
				NewQueryParam("force_refresh", "boolean", false, "force refresh flag for querying users").Default(false),
				NewHeaderParam("X-Special-Flag", "string", true, "a special flag in header, which must be set for querying users"),
			).
			Responses(
				NewResponse(200, "_Result<_Page<UserDto>>"),
			),

		NewGetOperation("/user/{id}", "Query the specific user").
			Tags("User").
			Securities("jwt").
			Params(
				NewPathParam("id", "integer#int64", true, "user id"),
			).
			Responses(
				NewResponse(200, "_Result<UserDto>"),
			),

		NewPutOperation("/user", "Update the authorized user").
			Tags("User").
			Securities("jwt").
			Params(
				NewBodyParam("param", "UpdateUserParam", true, "update user param"),
			).
			Responses(
				NewResponse(200, "Result"),
			),

		NewDeleteOperation("/user", "Delete the authorized user").
			Tags("User").
			Securities("jwt").
			Responses(
				NewResponse(200, "Result"),
			),
	)

	AddDefinitions(
		NewDefinition("Result", "Global response").
			Properties(
				NewProperty("code", "integer#int32", true, "status code"),
				NewProperty("message", "string", true, "status message"),
			),

		NewDefinition("_Result", "Global generic response").
			Generics("T").
			Properties(
				NewProperty("code", "integer#int32", true, "status code"),
				NewProperty("message", "string", true, "status message"),
				NewProperty("data", "T", true, "response data"),
			),

		NewDefinition("_Page", "Global generic page response").
			Generics("T").
			Properties(
				NewProperty("page", "integer#int32", true, "current page"),
				NewProperty("limit", "integer#int32", true, "page size"),
				NewProperty("total", "integer#int32", true, "total count"),
				NewProperty("data", "T[]", true, "response data"),
			),

		NewDefinition("LoginParam", "Login parameter").
			Properties(
				NewProperty("username", "string", true, "username"),
				NewProperty("password", "string", true, "password"),
			),

		NewDefinition("RegisterParam", "Register parameter").
			Properties(
				NewProperty("username", "string", true, "username"),
				NewProperty("password", "string", true, "password"),
			),

		NewDefinition("UpdateUserParam", "Update user parameter").
			Properties(
				NewProperty("username", "string", true, "username"),
				NewProperty("bio", "string", true, "user bio"),
				NewProperty("gender", "string", true, "user gender").Enum("Secret", "Male", "Female"),
				NewProperty("birthday", "string#date", true, "user birthday"),
			),

		NewDefinition("LoginDto", "Login response").
			Properties(
				NewProperty("user", "UserDto", true, "authorized user"),
				NewProperty("token", "string", true, "access token"),
			),

		NewDefinition("UserDto", "User response").
			Properties(
				NewProperty("id", "integer#int64", true, "user id"),
				NewProperty("username", "string", true, "username"),
				NewProperty("bio", "string", true, "user bio"),
				NewProperty("gender", "string", true, "user gender").Enum("Secret", "Male", "Female"),
				NewProperty("birthday", "string#date", true, "user birthday"),
			),
	)

	_, _ = SaveSwaggerYaml("./docs/api3.yaml")
	_, _ = SaveSwaggerJson("./docs/api3.json")
	_, _ = SaveApib("./docs/api3.apib")
}

References

goapidoc's People

Contributors

aoi-hosizora avatar

Stargazers

 avatar

Watchers

 avatar  avatar

goapidoc's Issues

Add Get methods and add more Set methods

Sometimes I need to update some properties for existed value.
So it is necessity to use Get methods and use more Set methods to update those.

func RuntimeUpdateSwaggerSpec() {
	// config.Configs().Meta.Port
	host := goapidoc.GetDocument().GetHost()
	goapidoc.GetDocument().Host(host)
}

Complete the generate test

Complete the TestGenerate, not just use the if err != nil {}.

goapidoc/generate_test.go

Lines 383 to 399 in db16945

_, err := GenerateSwaggerYaml("./docs/api.yaml")
if err != nil {
log.Println(err)
t.Fatal("yaml")
}
_, err = GenerateSwaggerJson("./docs/api.json")
if err != nil {
log.Println(err)
t.Fatal("json")
}
_, err = GenerateApib("./docs/api.apib")
if err != nil {
log.Println(err)
t.Fatal("apib")
}

Add more test for apitype.go

Fix some potential bugs in apitype.go and rewrite test with test cases.

Some ugly tests now:

goapidoc/generate_test.go

Lines 105 to 114 in cf47f71

def := &Definition{
generics: []string{"T", "U", "V"},
properties: []*Property{
{typ: "inT[]"},
{typ: "O<inT[], T[], T, inT<int>>"},
{typ: "T"},
{typ: "tT<T<tT>[][], T>[]"},
{typ: "TtT<T,tT[],T[][]>[]"},
},
}

goapidoc/generate_test.go

Lines 162 to 167 in cf47f71

newDefs := prehandleGenericList(defs, []string{
"Result<Page<User>>",
"Result3<User, Page<Result2<Login, Page<Login>>>, String[]>",
"Integer",
"Result2<String, Result2<String, String>>",
})

[BUG] bug with has multiple tags in path

Demo code:

goapidoc.NewPath("GET", "/v1/policy", "查询所有策略").
	WithTags("Policy").
	// WithTags("Administration").
	WithSecurities("Jwt").
	WithResponses(goapidoc.NewResponse(200).WithType("_Result<_Page<PolicyDto>>")),

The first tags (policy) will be ignore and only the last tag will be shown in spec.json.

Failed to parse unresolved generic parameter in swagger-ui

Errors
Hide
Resolver error at definitions._Page.properties.data.items.$ref
Could not resolve reference because of: Could not resolve pointer: /definitions/T does not exist in document
Resolver error at definitions._Result.properties.data.$ref
Could not resolve reference because of: Could not resolve pointer: /definitions/T does not exist in document
"data": {
  "type": "array",
  "required": true,
  "description": "page data",
  "items": {
    "originRef": "T",
    "$ref": "#/definitions/T"
  }
},

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.