I find TypeScript valuable for my development workflow. It prevents bugs by recognizing inconsistent assumptions in my code and highlighting them, giving me more confidence of my code.
But, TypeScript can’t type-check beyond the codebase that it runs at compile time. A fetch
call will always be any
(or unknown
) because there is no way for TypeScript to know what could be the response in runtime. Of course, we can play pretend by manually declare the type of the response, but it is an ongoing manual work because the API we call may change. And being a programmer, we hate manual works because we eventually make mistake and we’re lazy.
There are few ways to overcome this TypeScript’s limitation, such as using GraphQL (with GraphQL codegen) or gRPC (with tRPC). Those tools are powerful and easy to setup, but in practice they are hard to adopt because they require a change of the API server tech stack, a privilege many of us do not have.
However, if you’re willing to study and assemble multiple libraries together, there is a tool that could solve this problem without changing backend tech stack: OpenAPI.
What is OpenAPI
OpenAPI is a specification that aims to standardize how all REST APIs are described, regardless of programming language used to create the API. Document created based on OpenAPI is called OpenAPI doc, and it is a JSON object, which may be written either in JSON or YAML format. OpenAPI is sometimes also referred to as “Swagger”. 1
OpenAPI doc is usually created in two ways:
- it is generated with code annotation created for the programming language or framework used by the server. For example, NestJS supports generation of the OpenAPI document with its first-party library, SpringFox generates OpenAPI document for API server built with Spring framework.
- it is handwritten by the API developers (directly or indirectly using OpenAPI editors) and then used to generate stub for the API code
Common uses of OpenAPI doc
The most common usage of OpenAPI doc is to generate a live HTML page using swagger-ui or similar tools like Redoc, making it easy for anyone to explore the endpoints of the server without needing to delve into the code. If you never seen the UI before, you can see an example here.
The page allows user to make actual requests to the server, which makes it a cheap way for power users like technical supports to invoke API requests, instead of requiring additional engineering effort to build a UI.
As OpenAPI doc describes the expected request and response of each endpoint clearly, it is sometimes used as a design document to align expectation and understanding between developers before any coding. Many teams also use OpenAPI doc with their development and testing tools like Postman, which then be used for API testing. If the quality of the OpenAPI doc includes good description of what each endpoint does, API testing could be done fully in a self-service manner, without manual communication between the tester and the API developer.
Less common uses of OpenAPI doc
There are more opportunities to use OpenAPI docs that are lesser used, but still very useful:
Client SDK generation
SDK (software development kit) is a set of tools that is provided by a service that you uses. For example, AWS provides AWS SDK to developers as a convenient way to access AWS functionalities in different programming languages. A SDK of an API is usually referred to a class or package that calls the API under the hood, but implemented in the client programming language to improve the developer experience, as it would supports the features of the language such as type checking.
There are many open-source tools to convert OpenAPI doc to generate client SDK of different programming languages, including Typescript. For example, you can use openapi-typescript-codegen 2 to generate Typescript interfaces and API request function calls, so you can properly type check your code related to the network requests. This process can be automated so that every time the API that you’re calling update its OpenAPI doc, the code generation will be rerun and the code will be updated automatically. Breaking changes that affect your usage, such as removing a field that your frontend code is using, will resulted in a type error.
Mock server generation
Similar to SDK generation, mock server generation is another types of code generation from OpenAPI spec, but for different purpose. Mock server code generated from OpenAPI spec is usually used for testing, where developer can start a server to simulate API behavior when running test for frontend application that call the API. In practice, how useful of this would hugely depends on the quality of the OpenAPI spec, e.g. the examples included in the spec, because the response returned by the mock server relies on that.
API Gateway configuration
API gateway is a common component in microservice architectures, where it sits between the client and all the backend services.
With OpenAPI doc, we can include certain requirements of our API operation, which can then be used to configure the API gateway. For example, we can specify the rate limits for a operation in our API. When the OpenAPI doc change, an automatic program can detects it and configures the API gateway rate-limiting rules accordingly.
Edge function generation
Edge functions are lambda functions that run at the “edge”, somewhere near to your users. If you’re not familiar with edge functions, one way to think about it is that it is like CDN, but for lambda functions. Edge functions allows us to run code closer to our users, provide faster response.
As authorization requirements and request body schema could be described in OpenAPI doc, we can technically use Open API doc to generate edge functions that validate the request payload at the edge, before the request reaches our server.
Breaking change detection
When an API is used by many clients, such as in a large company or the API is released to external parties, it is crucial to avoid breaking changes without proper planning and announcement. As it is easy to parse OpenAPI spec, there are libraries (such as this openapi-diff
package) to detect breaking changes of the API such as:
- removal of path
- removal of method
- addition of required fields in request payload
- removal of fields in response
To make this automation easier, it is one of the best practices to commit the OpenAPI doc into your source control.
Conclusion
For backend developers that maintain REST API server, OpenAPI integrates with many tools to help with their developments and communications with other stakeholders. For frontend developers, it allows us to generate code that we prefer not to write manually. OpenAPI may not sounds as cool as GraphQL or gRPC, but because it integrates well with many programming languages and frameworks, it may be the only feasible solution in companies that use REST APIs or multiple backend languages.