Verify Unknown APIs with an Object Schema
Zod is commonly used for verifying unknown APIs.
In this example, we're fetching a person from the Star Wars API:
Note the call to
PersonResult.parse() that takes in the data from the fetch request.
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:
const PersonResult = z.unknown();
Running the Test
console.log(data) inside of the fetch function, we can see there's loads of stuff included in the API response when the test is run. There's the character's name, but there's also information about their eye color and the films they appear in, and other data we're not interested in at the moment.
The test does pass– it's the issue of
PersonResult being an unknown type that we need to fix.
Referencing Zod's Object schema documentation, construct something that includes
name and allows the types to parse.
Matt Pocock: We're now going to look at another really common use case in Zod, which is verifying unknown APIs. Here, we're calling an API inside
fetchStarWarsPersonName, which is we're calling
swapi.dev.API people. We're calling a res API endpoint, and then turning it into JSON.
This data here, it's typed as any, which is like an unknown data type. We don't really know what data is. We know. We can go and look on the swapi.dev documentation and we can look at the data. We can also, by the way, because we're actually calling it inside these tests, we just console.log(data).
We can look inside the console, and you'll see that there's loads and loads of stuff here. We're grabbing C-3PO in the second one, and we're grabbing Luke Skywalker in the first one. It looks like our tests are actually passing, but the issue is that this data type this PersonResult, which we're using to parse the data from this API, it's just returning unknown.
That means that we can't access the name property on something that we don't know what it is. Your challenge is to use the tools that you have in Zod, especially the object tools, to try and construct something that at least has a name on it so we can make the types parse.