Zod Section 10 exercises
Problem

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:


export const fetchStarWarsPersonName = async (id: string) => {
const data = await fetch("<https://swapi.dev/api/people/>" + id).then((res) =>
res.json(),
);
co

Loading exercise

Transcript

Matt Pocock: 0:00 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.

0:20 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).

0:39 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.

0:59 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.