The pragmatic way for validating API Request & Response (Part - 1)

29 Oct 2024

If you have developed APIs before, you know one of the tiresome work is to write logic for validating the Data that is coming from frontend, like …

  • If the keys are available in request.body

  • Is it a valid number ..?

  • is the array containing a minimum of 1 element ..?

For example let’s see an example of traditional validation function for an API request

Traditional way of validating API requests


validateUser function might look like below

Validation Logic for user request body


The problems with this kind of validation is that it is
— Not reusable
— Changes often based on the nature of API
— Prone to error
— Every developer will have their own validation logic
— Mainly, if I change something here at backend part, I need to make sure frontend adheres to it, There is not strict contract between frontend and backend.



Zod is a modern schema validation library for typescript which exactly solves the above addressed problems, it supports all the types that you might use on a day to day basis and also has support for constructing complex types. Apart from schema validation it also supports static type inference & Error handling out of the box. This blog has two parts, in this section we’ll go through the basic usage of Zod and in second part we’ll discuss Zod customizations for our own use case.

Let’s look at the same create_user example, but with the power of Zod

First we need to create a schema for the user


then we just need to use the schema to parse the request body we using .safeParse() which will return either success or error for further processing



Looks simple right , but it’s powerful, now you can reuse it wherever you want , either inside the same codebase or in a shared repository because it comes with zero dependencies. Let’s discuss the Pragmatic way of error handling, tricks and tips in part 2.

Yeswanth Rajakumar

Yeswanth Rajakumar

Fullstack Developer

Fullstack Developer

Connect with me

Connect with me

We are located at

India

United Kingdom

Netherlands

Contact

talkto@steam-a.com

+91 99444 33392

+44 74034 56793

We are located at

India

United Kingdom

Netherlands

Contact

talkto@steam-a.com

+91 99444 33392

+44 74034 56793

We are located at

India

United Kingdom

Netherlands

About Company

Follow us for exciting updates

© 2024 Iris

About Company

Follow us for exciting updates

© 2024 Iris

About Company

Follow us for exciting updates

© 2024 Iris