</>StackKit
</>StackKit

Developer tutorials & guides

black flat screen computer monitor
TypeScript

Type-safe API calls with TypeScript and Zod

A comprehensive guide to Type-safe API calls with TypeScript and Zod.

S
StackKit Team
May 12, 20264 min read
#typescript#tutorial#guide#zod#api#validation
{
  "title": "Type-safe API calls with TypeScript and Zod",
  "description": "Learn how to make type-safe API calls using TypeScript and Zod, ensuring robust and maintainable code.",
  "content": "# Type-safe API calls with TypeScript and Zod

## Introduction

When building modern web applications, making API calls is an essential part of the development process. However, ensuring the type safety of these API calls can be a daunting task, especially when working with complex data structures. In this tutorial, we will explore how to make type-safe API calls using TypeScript and Zod.

TypeScript provides optional static typing and other features that help developers catch errors early and improve code maintainability. Zod, on the other hand, is a TypeScript-first schema validation library that allows you to define the shape of your data using a simple and intuitive API.

By combining the power of TypeScript and Zod, you can ensure that your API calls are type-safe, robust, and maintainable.

## Setting up the Project

To get started, create a new TypeScript project using your preferred method (e.g., using `tsc --init` or a tool like Create React App). Install Zod using npm or yarn:

```bash
npm install zod

Next, create a new file called api.ts to define your API calls.

Defining API Calls with Zod

Let's assume we have a simple API that returns a list of users. We can define the shape of the API response using Zod's z.object method:

import { z } from 'zod';

const userSchema = z.object({
  id: z.number(),
  name: z.string(),
  email: z.string().email(),
});

const usersSchema = z.array(userSchema);

In this example, we define a userSchema that consists of an id, name, and email field. The email field is validated using Zod's email() method to ensure it conforms to a standard email format.

We then define a usersSchema that represents an array of userSchema objects.

Making Type-safe API Calls

Now that we have defined our API schema, we can make type-safe API calls using the fetch API and Zod's parse method:

async function getUsers(): Promise<typeof usersSchema> {
  const response = await fetch('https://api.example.com/users');
  const data = await response.json();

  return usersSchema.parse(data);
}

In this example, we define a getUsers function that fetches the list of users from the API and parses the response data using the usersSchema. The parse method returns a type-safe object that conforms to the usersSchema shape.

Handling Errors

When making API calls, it's essential to handle errors properly to ensure your application remains robust and maintainable. Zod provides a parse method that throws a ZodError if the data fails to conform to the schema.

We can handle errors by wrapping our API call in a try-catch block:

async function getUsers(): Promise<typeof usersSchema> {
  try {
    const response = await fetch('https://api.example.com/users');
    const data = await response.json();

    return usersSchema.parse(data);
  } catch (error) {
    if (error instanceof z.ZodError) {
      console.error('API data failed to conform to schema:', error);
    } else {
      console.error('API error:', error);
    }
    throw error;
  }
}

In this example, we catch any errors that occur during the API call and check if the error is a ZodError. If it is, we log an error message indicating that the API data failed to conform to the schema. Otherwise, we log a generic API error message.

Conclusion

In this tutorial, we explored how to make type-safe API calls using TypeScript and Zod. By defining our API schema using Zod's z.object method and making API calls with the fetch API and Zod's parse method, we can ensure that our API calls are robust, maintainable, and type-safe.

By handling errors properly using try-catch blocks and logging error messages, we can ensure that our application remains stable and provides a good user experience.

Remember to always validate your API data using a library like Zod to ensure type safety and prevent common errors. Happy coding!" } ```

#typescript#tutorial#guide#zod#api#validation