Zod Tutorial (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(),
  );

  const parsedData = PersonResult.parse(data);

  return parsedData.name;
};

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:

const PersonResult = z.unknown();

Running the Test

If we 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.

Challenge

Referencing Zod's Object schema documentation, construct something that includes name and allows the types to parse.

Transcript

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.