Swagger automatically generates Api documentation tutorial, super detailed!

The benefits of automatically generating API documentation are self-evident. It can be provided to your team or external collaborators, so that API users can accurately call your API . In order to reduce errors caused by manually writing documents, many API developers will prefer to find some good ways to automatically generate API documents. This article will introduce some commonly used document generation tools: Tapir, an open source tool, and Apifox, a commercial product.

Introduction

Tapir is an open source API design and documentation tool, which is based on the OpenAPI specification (also known as the Swagger specification) and provides a higher level of abstraction that can help developers design and document RESTful APIs more easily .

Tapir displays the different endpoints and parameters of the API in a visual way, and provides rich editing functions and automatic API document generation tools, which can generate easy-to-read and understand documents, and also provides a variety of export formats (such as OpenAPI specification, Markdown, etc.) to meet different needs.

In addition to API design and documentation, Tapir also provides testing and mocking capabilities for APIs, which can simulate API responses and test them. It also provides the ability to automatically generate client code, allowing developers to use the API more quickly.

Why use Tapir

1. Provide type safety: One of the main features of Tapir is to provide type-safe API definitions. You can use Scala's strong type checker to check the correctness of API definitions, thereby reducing runtime errors caused by incorrect API definitions.

import sttp.tapir._import sttp.tapir.generic.auto._import sttp.tapir.json.circe._import io.circe.generic.auto._import java.util.UUIDcase class User(name: String)val paging: EndpointInput[(UUID, Option[Int])] =   query[UUID]("start").and(query[Option[Int]]("limit"))// we can now use the value in multiple endpoints, e.g.:val listUsersEndpoint: PublicEndpoint[(UUID, Option[Int]), Unit, List[User], Any] =   endpoint.in("user" / "list").in(paging).out(jsonBody[List[User]])

2. Ease of testing : Since Tapir provides type-safe API definitions, you can use Scala's testing framework to easily write test cases and ensure that your API can run correctly under various circumstances. This can reduce errors and bugs in the development process and improve development efficiency.

3. Easy to maintain: Tapir provides an easy-to-maintain API definition because it decomposes the API definition into independent, composable parts. This means you can easily update parts of the API without affecting the entire API definition.

4. Generate client and server code: Tapir can be used to convert API definitions into various types of client and server code, including HTTP client and server, Scala and Java client and server, etc. This reduces the effort of manually writing client and server code, while reducing the potential for errors and bugs.

5. Automatically generate API documentation: Tapir provides a method to automatically generate API documentation, which makes the creation of API documentation simple and easy to maintain. You can choose to generate documentation from the API definition at runtime, or bundle the API definition with the documentation at build time.

Use Tapir Quickly

add dependencies

"com.softwaremill.sttp.tapir" %% "tapir-core" % "1.2.9"

Define an endpoint (Endpoint)

case class Status(uptime: Long)


val statusEndpoint: PublicEndpoint[Unit, ErrorInfo, Status, Any] =
   baseEndpoint.in("status").out(jsonBody[Status])

The following is an example of pagination

import sttp.tapir._
import java.util.UUID

case class Paging(from: UUID, limit: Option[Int])


val paging: EndpointInput[Paging] =   query[UUID]("start").and(query[Option[Int]]("limit"))    .map(input => Paging(input._1, input._2))(paging => (paging.from, paging.limit))

Integrated web framework

import sttp.tapir._

import sttp.tapir.server.akkahttp.AkkaHttpServerInterpreter

import scala.concurrent.Future

import akka.http.scaladsl.server.Route

import scala.concurrent.ExecutionContext.Implicits.global

def countCharacters(s: String): Future[Either[Unit, Int]] = 

  Future.successful(Right[Unit, Int](s.length))
  
val countCharactersRoute: Route =   AkkaHttpServerInterpreter().toRoute(countCharactersEndpoint.serverLogic(countCharacters))  
  
val countCharactersEndpoint: PublicEndpoint[String, Unit, Int, Any] =   endpoint.in(stringBody).out(plainBody[Int])  val countCharactersRoute: Route =   AkkaHttpServerInterpreter().toRoute(countCharactersEndpoint.serverLogic(countCharacters))

Generate Swagger UI

Generated descriptions can be shared using user interfaces such as Swagger or Redoc.

"com.softwaremill.sttp.tapir" %% "tapir-swagger-ui-bundle" % "1.2.9"
import sttp.tapir._import sttp.tapir.swagger.bundle.SwaggerInterpreterimport sttp.tapir.server.akkahttp.AkkaHttpServerInterpreterimport scala.concurrent.Futureimport scala.concurrent.ExecutionContext.Implicits.globalval myEndpoints: List[AnyEndpoint] = ???// first interpret as swagger ui endpoints, backend by the appropriate yamlval swaggerEndpoints = SwaggerInterpreter().fromEndpoints[Future](myEndpoints, "My App", "1.0")// add to your akka routesval swaggerRoute = AkkaHttpServerInterpreter().toRoute(swaggerEndpoints)

Generate endpoint according to yaml

addSbtPlugin("com.softwaremill.sttp.tapir" % "sbt-openapi-codegen" % "1.2.9")
Enable the plugin for your project in the build.sbt:
enablePlugins(OpenapiCodegenPlugin)
Add your OpenApi file to the project, and override the openapiSwaggerFile setting in the build.sbt:
openapiSwaggerFile := baseDirectory.value / "swagger.yaml"

Here are some configuration instructions:

setting default value description
openapiSwaggerFile baseDirectory.value / “swagger.yaml” The swagger file with the api definitions.
openapiPackage sttp.tapir.generated The name for the generated package.
openapiObject TapirGeneratedEndpoints The name for the generated object.

While Tapir is a very useful tool for API design and documentation, it has some drawbacks:

  1. High learning cost: Although Tapir offers a wealth of features and automation tools, its high-level abstractions and complex user interface can confuse beginners. Therefore, learning how to use Tapir takes time and experience.
  2. Rely on the OpenAPI specification : Tapir is based on the OpenAPI specification, so the prerequisite for using Tapir is to have a certain knowledge and understanding of the OpenAPI specification. If you are not familiar with the OpenAPI specification, you may need to spend extra time learning the specification and related concepts.
  3. Code generation may be inaccurate: Although Tapir provides the function of automatically generating client code, there may be some problems in the generated code, such as inaccurate comments, irregular code structure, etc., which may require developers to spend extra time Adjust and optimize.
  4. Integration may be difficult: Since Tapir is a separate tool, it needs to be integrated with other development tools (such as editors, version control systems, etc.), which may require additional setup and configuration, which may add some complexity.

More ways to automatically generate API documentation.

 

Guess you like

Origin blog.csdn.net/LiamHong_/article/details/131938423