The benefits of automatically generating API documentation are self-evident. It can provide your team or external collaborators with easy access to your API, enabling users to make accurate calls to your API. In order to reduce errors caused by manual documentation, many API developers prefer to find good ways to automatically generate API documentation. This article will introduce some commonly used documentation generation tools: the open-source tool Tapir and the professional product Apidog.
What is Tapir
Tapir is an open-source API design and documentation tool that is based on the OpenAPI specification (also known as the Swagger specification) and provides higher-level abstractions to help developers design and document RESTful APIs more easily.
Tapir displays different endpoints and parameters in a visual way, offering multiple edition functions and automation API documentation generation tools.
Tapir displays the different endpoints and parameters of an API in a visual way and provides rich editing features and automated API documentation generation tools that can generate easily readable and understandable documents. It also offers various export formats (such as OpenAPI specification, Markdown, etc.) to meet different needs. In addition to API design and documentation, Tapir also provides testing and simulation functions for APIs, allowing developers to simulate API responses and conduct testing. It also offers the ability to automatically generate client code, which enables developers to use the API more quickly.
Why to UseTapir
- Provides type safety: One of the main features of Tapir is providing type-safe API definitions. You can use Scala's strong type checker to verify the correctness of the API definition, 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]])
- Easy to test: Since Tapir provides type-safe API definitions, you can easily write test cases using Scala's testing framework and ensure that your API runs correctly in various situations. This can reduce errors and bugs during the development process and improve development efficiency.
- Easy to maintain: Tapir provides an easy-to-maintain API definition approach by decomposing the API definition into independent, composable parts. This means that you can easily update certain parts of the API without affecting the definition of the entire API.
- Generates client and server code: With Tapir, you can convert API definitions into various types of client and server code, including HTTP clients and servers, Scala and Java clients and servers, etc. This can reduce the workload of manually writing client and server code, while also reducing the likelihood of errors and bugs.
- Generates API documentation automatically: Tapir provides a method for automatically generating API documentation, which makes it simple and easy to maintain the documentation. You can choose to generate documentation from the API definition at runtime or bind the API definition with the documentation at build time.
Getting Started with Tapir
Step 1. Add dependency
"com.softwaremill.sttp.tapir" %% "tapir-core" % "1.2.9"
Step 2.Define an Endpoint
case class Status(uptime: Long) val statusEndpoint: PublicEndpoint[Unit, ErrorInfo, Status, Any] = baseEndpoint.in("status").out(jsonBody[Status])
Here 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))
Integrate with a 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))
Step 3. Generate Swagger UI
The generated description can be shared through a user interface 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)
Step 4. Generate Endpoint based on 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"
There are setting description attachments.
|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.|
Free and User-Friendly Business Product: Apidog
From in-depth using Tapir, some limitation are as follows. Despite providing rich functionality and automation tools, Tapir's advanced abstractions and complex user interface may be confusing for beginners. Moreover, Tapir is based on the OpenAPI specification, so using Tapir requires some understanding and knowledge of the OpenAPI specification. If you are not familiar with the OpenAPI specification, you may need to spend additional time learning the specification and related concepts.
Although Tapir provides the functionality of automatically generating client-side code, the generated code may have some problems, such as inaccurate comments and non-standard code structure. Since Tapir is a standalone tool, it needs to be integrated with other development tools (such as editors and version control systems), which may require additional settings and configurations and may add some complexity.
For professional API developers or development teams accustomed to the Design First approach, we recommend the more user-friendly API collaboration platform, Apidog. Apidog is a comprehensive API management platform that provides API documentation, API debugging, API mock, and API automation testing capabilities, and can solve data synchronization problems between multiple systems. Apidog is a solution to interface management problems, supporting use case management, data model definition, automatic verification of data structures during debugging, and visualization of setting assertions and extracting variables.
The Benefits of Apidog
In addition to basic capabilities, Apidog also provides many features that not only satisfy developers' daily API development, debugging, and testing scenarios but also support developers in managing and sharing API documentation and generating code based on API documentation.
Online API Documentation
Apidog provides an online platform for creating, testing, and managing APIs, making it easier for developers to use APIs. One of Apidog's main features is its support for online API documentation.
With Apidog, you can easily create and maintain clear and comprehensive documentation for your APIs. The documentation is generated based on API definitions and follows the OpenAPI and JSON Schema standards. The documentation includes detailed information about endpoints, request parameters, response data, and other relevant information.
You can also customize the documentation to meet your specific needs and easily share it with others. Apidog's documentation is not just text; it also includes interactive features such as trying out the server, viewing request and response examples, and more. These features help developers better understand and quickly test APIs. Apidog also provides real-time updates, so any changes made to the API will be promptly reflected in the online documentation.
Apidog also has the ability to automatically generate code, generating code snippets for almost all popular programming languages and frameworks (over 130 in total). This can save developers a lot of time and effort as they do not have to start from scratch. Code templates can be customized according to developers' preferences, making it more flexible.
Another important feature of Apidog is its import/export functionality. Apidog is committed to continuously improving the API ecosystem by providing seamless integration. With this feature, you can directly export various data formats such as OpenAPI, Markdown, HTML, and more for further API work. You can also import different data types such as OpenAPI, Postman, YApi, and more, making it easier to migrate projects.
Automatically generate documentation with IDEA plugin.
It is worth mentioning Apidog Helper, which is an IDEA plugin that helps developers automatically parse code comments and quickly generate API documentation. Apidog Helper is based on javadoc (Java), KDoc (Kotlin), and ScalaDoc (Scala) to parse API documentation, and supports protocol frameworks such as Spring Boot, Swagger, and JAX-RS. It can basically achieve zero-invasion code automatic generation of interface documents.
Using Apidog Helper in IDEA, developers can synchronize documents to the Apidog project with just one click, without switching tools, and can update and synchronize documents to other team members within the team. Automatic parsing of comments, quick synchronization of documents, debugging within IDEA, and convenient team collaboration with Apidog.