Introduction
Type-safe APIs are becoming increasingly popular in web development. This is because they bring several benefits to both the developer and the application.
In Web applications, a type-safe API describes an API where the request and response data are explicitly defined using types. Some benefits of using a type-safe API in applications include increased data security and integrity, improved performance, and enhanced developer experience.
Using type-safe APIs greatly benefits developers because it makes it easier to find bugs, improves code completion error checking and significantly reduces runtime errors.
In this article, we shall review a few libraries that come in handy for building type-safe Web Applications.
Yup
Yup is a popular open-source library for schema-based validation. It is a schema builder for runtime value parsing and validation, making it easy to define the objects' expected structure and data types.
Here are some key functionalities of Yup;
Concise schema definition: Yup provides intuitive syntax similar to JSON to define object schemas. It also allows schema definition to declare required and optional fields and apply validation rules like length, patterns, and custom validation logic.
Validation: Yup validates JavaScript objects against defined schemas, catching invalid data early. It handles both synchronous and asynchronous validations, giving you flexibility. The built-in async validation support makes it easy to model server-side and client-side validation equally well. It also provides clear and concise messages that make debugging seamless.
Powerful typescript support: This feature makes Yup infer static types from schema or ensure the schema correctly implements a type.
Extensibility: Yup also allows developers to add their type-safe methods and schema.
You can check out the package’s documentation here.
Joi
Joi is a powerful library for building type-safe web application APIs in Javascript and Node.js. It is one of the oldest libraries for building type-safe applications, with its first version released in 2013. Although originally released as an open-source library, it is now maintained by Automattic, the company behind Wordpress.com.
Here are a few beautiful features about Joi
Schema Definition: Joi uses an expressively rich schema language to define data structures and validation rules. It supports various data types, nested arrays, objects, and complex validation logic. Developers can customise the schema with options like conditional validation, custom error messages, and language localisation.
Data validation: It catches invalid data early in development, preventing errors and improving data integrity. It makes debugging easy by providing detailed error messages that pinpoint the exact location and nature of validation failures.
Performance: Joi is highly optimised for efficiency, especially with large datasets and complex validation rules. It leverages asynchronous validation and caching mechanisms for improved performance in large datasets. It also supports promises and async/await for non-blocking validation.
You can check out their documentation here.
Zod
Zod is more popular within typescript projects. It is a popular library for type-safe schema validation. It focuses more on offering a developer-friendly experience. This is possible because it offers the following features.
Type Safety: Zod offers typescript-first schema validation with static type inference. This means it leverages typescript types to define schemas, ensuring data is consistent with the specified structure. It also integrates seamlessly with typescript, improving data type inference and automatic type checking. This static type safety benefit catches potential errors at compile time instead of runtime like other packages.
Performance: Zod executes efficiently by avoiding unnecessary code execution through caching and other optimisation techniques. It suits applications with complex schemas, large datasets or high throughputs.
Immutable Schemas: In Zod, when changes are made to existing schemas, they do not modify or affect existing data, ensuring data integrity and predictability.
You can check out their documentation here.
Superstruct
This library is relatively new but is highly regarded. Like Zod, it is a type-safe schema validation, particularly within Typescript. Typescript GraphQL inspired its type annotation API, Go and Flow, making the API easy to understand. It was first released in 2019, and it is considered fully open-source. It offers the following features:
Strong type safety: It leverages typescript types directly to define schemas and offers strong data integrity and consistency. It provides static type-checking during development and catches errors at runtime.
Composability: It also allows the building of complex schemas by composing smaller reusable schema units. It also enables the sharing and reusability of small components across different parts of the codebase, which helps improve code organisation and maintainability for large-scale projects.
Immutable schemas: Similar to Zod, Superstruct allows changes to the schema without altering the data. This helps improve the application's scalability and predictability.
You can check out Superstruct documentation here.
tRPC
Compared to other libraries, tRPC is relatively new. However, it is primarily geared towards full-stack typescript development. A beautiful thing about tRPC is that it has no build or compile steps, meaning there is no code generation, runtime bloat, or build step. It also has zero dependencies; hence, it is a lightweight package. Some of the features tRPC offers include
Automatic Typesafety: tRPC was made to ease building typesafe end-to-end API. When a change is made to a schema on the server, tRPC will warn you of potential errors on the client before even saving the file. This leads to the development of a more reliable, robust API
Serverside code organisation: tRPC encourages server-side code organisation around well-defined functions. This promotes readability and maintainability for large code bases, making scaling the serverside codes easy. It also makes the process of testing the API logic seamless. tRPC also provides middleware that handles errors, logging, and other common tasks.
Automatic code generation: tRPC offers automatic code generation for client-side interfaces and boilerplate code, reducing repetitive code. It also auto-compiles API server code, giving developers confidence in their application’s endpoints.
Framework Agnostic: tRPC is compatible with all Javascript frameworks and runtimes. It is also easy to add to your existing projects. It also provides adapters for popular javascript libraries and frameworks like React, Nextjs, Solidjs, Svelte, Express, Fastify, and AWS Lambda.
Function-Based API Definition: This is one of tRPC's key outstanding features. It defines endpoints using Javascript functions instead of HTTP methods used in the traditional REST API. This approach streamlines API development by reducing boilerplate code and promoting code organisation. It also allows for more flexibility in API structure compared to rigid REST conventions.
tRPC is an open-source project whose active community contributes to its rapidly growing popularity. You can check out their documentation here.
Ts-rest
Ts-rest is another excellent library that makes the process of building type-safe API in typescript. It offers a simple way to define a contract for API routes. The application can implement and consume this without stress or extra code generation. Here are some of ts-rest key features:
Type safety: Ts-rest offers strong type safety through a typescript interface and request and response structure annotations. This leads to improved code quality and catch potential.
REST-Based API definition: Unlike tRPC, ts-rest uses the conventional REST approach for defining HTTP methods like GET, POST, PUT, and DELETE. This familiarity is usually beneficial for developers with experience working with REST APIs. Ts-rest supports various content types (JSON, form data, multipart) and provides common task middleware.
Full Optional OpenAPI integration: Ts-rest can automatically generate OpenAPI schema and documentation based on the API definitions. This allows developers to document API structure and data contracts for client-side applications and third-party tools. Also, this generated OpenAPI schema can be used to generate client-side Typescript code automatically to interact with the API. This shortens development time, makes client-side application development easier, and allows developers to focus on the application's features.
Ts-rest is an open-source project, and it has a fast-growing community. You can check out their documentation here.
Ajv
Ajv is specifically designed to validate JSON schema. This means it compares the application JSON data against defined schemas. Ajv offers the following features:
JSON Schema Language Support: This is its key feature. Ajv supports JSON schema drafts 04, 06, 07, 2019-09, and 2020-12 while offering the different flexibilities required for each. It provides a rich expression language for defining complex validation rules and conditions. Some of these keywords include required type, pattern, and additional properties.
Performance: Ajv works efficiently with large data sets. It utilises caching mechanisms and asynchronous validation for improved performance. According to the JSON-schema, jsck, z-schema, and themis benchmarks, Ajv is currently the fastest and most standard-compliant JSON validator.
Ajv seamlessly integrates with various web frameworks like Expressjs and Koa.js.
Ajv’s documentation is available here.
TypeBox
Like Ajv, TypeBox is a JSON Schema type builder and runtime validator for TypeScript. It allows you to define the expected structure of JSON data using familiar TypeScript types and then validate incoming data against those types at runtime.
Here are some key features of TypeBox:
JSON Schema Definition: TypeBox allows developers to use familiar typescript types to define the expected JSON data structure. The key difference between Ajv and TypeBox is that TypeBox uses TypeScript types for schema definition, providing type inference and IDE integration. Ajv on the other uses JSON Schema directly for defining validations.
Composability: TypeBox allows developers to build complex schemas from simpler and smaller ones for nested structures and diverse data representations. It also handles arrays, objects, and nested objects easily.
Clear Types Documentation: The typescript types are declared to act as a self-documenting schema, improving code readability. They also allow developers to add metadata like descriptions or examples to enhance schema documentation.
The documentation can be found here.
Class-Validator
Although this library is primarily for validating class instances in typescript and is not specifically designed for it, it can be handy in web application development, including APIs.
The Key feature of the class-validator library that is useful in developing typesafe applications:
Declarative validation: This feature allows developers to define validation rules on class properties using decorators like @IsString(), @IsNumber(), @isEmail() and @MinLength(8)
. This approach greatly improves code quality by enhancing readability, reducing boilerplate code and promoting clear mapping between data models and validation rules.
You can check out its documentation here.
feTS
feTS is a new library for building typesafe full-stack applications. This library makes building and consuming REST APIs easy without compromising type safety in client-server communication. The feTS client and server can be used to build full-stack applications. It can also be used independently. The independent use allows developers to adapt to their project’s specific needs.
Aside from providing type-safety, it also provides other features, which include:
JSON Schema Route Description: feTS utilises the JSON schema specifications for route description. This enables integration with any tool within the JSON Schema ecosystem.
OpenAPI integration: feTS utilises the OpenAPI specification for universal tool compatibility. Also, it generates an OpenAPI documentation UI using the Swagger-UI with the server out-of-the-box.
Versatile Server: The feTS server provides a superfast HTTP server that can be deployed and run anywhere with the power of the dependency @whatwg-node/server. Some servers where feTS can be deployed include the AWS Lambda, Azure Function, Bun, Node.js, Deno, Google Cloud Functions, Next.js, and μWebSockets.
You can learn more from the documentation here.
There are still a few more libraries in development. An example is Tempo by betwixt-labs.
Conclusion
So far, this article has covered some useful libraries for developing typesafe APIs. However, which one to use on your next project depends on your application's specific needs and peculiarities. For instance, if your application heavily depends on JSON schemas, your go-to library might be Ajv. If you want type-safety on both client and server, you might consider working with tRPC or ts-rest.
If you made it this far, I say thank you for reading through. I hope you found this article helpful. If you did, kindly like and share it with your friends and colleagues.
I would love to connect with you on Twitter | LinkedIn | Github.
Top comments (0)