✨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:
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:
The issue of PersonResult is an unknown type that we need to fix:
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:
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.
I hope you found it useful. Thanks for reading. 🙏
Let's get connected! You can find me on: