DEV Community

Nhan Nguyen
Nhan Nguyen

Posted on

1

Zod - TypeScript-first schema declaration and validation library #3

Image description

Verify Unknown APIs with an Object Schema

Zod is commonly used for verifying unknown APIs.

In the below example, we are fetching a person from the Star Wars API:

Image description

Note the call to PersonResult.parse() that takes in the data from the fetch request.

The PersonResult variable is created with z.unknown(). This tells us that our data is typed as any because we don't know what it is:

Image description

The issue of PersonResult is an unknown type that we need to fix:

Image description

We will change PersonResult into z.object(). This tool allows us to construct objects with the keys and types we want. In this case, we want the name which will be a string:

Image description

Inside of fetchStarWarsPersonName, our parsedData is now correctly typed and has a structure that Zod understands.

Recall that the response from the API call included lots of information we were not interested in.

Zod will strip away all of the keys that we aren't interested in, and gives us only the name.

Image description


I hope you found it useful. Thanks for reading. 🙏
Let's get connected! You can find me on:

Sentry blog image

How I fixed 20 seconds of lag for every user in just 20 minutes.

Our AI agent was running 10-20 seconds slower than it should, impacting both our own developers and our early adopters. See how I used Sentry Profiling to fix it in record time.

Read more

Top comments (0)

SurveyJS custom survey software

JavaScript Form Builder UI Component

Generate dynamic JSON-driven forms directly in your JavaScript app (Angular, React, Vue.js, jQuery) with a fully customizable drag-and-drop form builder. Easily integrate with any backend system and retain full ownership over your data, with no user or form submission limits.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay