Javascript

Level up your REST API's with JSON Schema

Dane Grant
5 min read
Dane - Level up your REST API's with JSON Schema
This article was written over 18 months ago and may contain information that is out of date. Some content may still be relevant, but please refer to official documentation for the latest information.

JSON Schema isn’t a hot topic that gets a lot of attention compared to GraphQL or other similar tools. I discovered the power of JSON Schema while I was building a REST API with Fastify. What is it exactly? The website describes it as “the vocabulary that enables JSON data consistency, validity, and interoperability at scale”. Or more simply, it’s a schema specification for JSON data. This article is going to highlight some of the benefits gained by defining a JSON Schema for a REST API.

JSON Schema Basics

Here’s an example of a simple schema representing a user:

{
  "$id": "<https://example.com/schemas/user>",
  "$schema": "<http://json-schema.org/draft-07/schema#>",
  "type": "object",
  "properties": {
    "firstName": {
      "type": "string"
    },
    "lastName": {
      "type": "string"
    },
    "email": {
      "type": "string",
      "format": "email"
    },
    "age": {
      "type": "integer"
    },
    "newsletterSubscriber": {
      "type": "boolean"
    },
    "favoriteGenres": {
      "type": "array",
      "items": {
        "type": "string"
      }
    }
  },
  "required": ["email"],
  "additionalProperties": false
}

If you’re familiar with JSON already, you can probably understand most of this at a glance. This schema represents a JSON object with some properties that define a User in our system, for example. Along with the object’s properties, we can define additional metadata about the object. We can describe which fields are required and whether or not the schema can accept any additional properties that aren’t defined on the properties list.

Types

We covered a lot of types in our example schema. The root type of our JSON schema is an object with various properties defined on it. The base types available to define in your JSON Schema map to valid JSON types: object, array, string, number, integer, boolean. Check the type reference page to learn more.

Formats

The email property in our example has an additional field named format next to its type. The format property allows us to define a semantic identification for string values. This allows our schema definition to be more specific about the type of values allowed for a given field. “hello” is not a valid string value for our email type.

Another common example is for date or timestamp values that get serialized. Validation implementations can use the format definition to make sure a value matches the expected type and format defined. There’s a section on the website that lists the various formats available for the string type.

Schema Structuring

JSON Schema supports referencing schemas from within a schema. This is a very important feature that helps us keep our schemas DRY. Looking back to our initial example we might want to define a schema for a list of users. We defined an id on our user schema of “user”, we can use this to reference that schema from another schema.

{
	"type": "array",
	"items": {
		"$ref": "<https://example.com/schemas/user>"
	}
}

In this example we have a simple schema that is just an array whose items definition references our user schema. This schema is exactly the same as if we defined our initial schema inside of "items": { }. The JSON Schema website has a page dedicated to structuring schemas.

JSON Schema Benefits

Validation

One of the main benefits of defining a schema for your API is being able to validate inputs, outputs. Inputs include things like the request body, URL parameters, and search parameters. The output is your response JSON data or headers. There are some different libraries available to handle schema validation. A popular choice and the one used by Fastify is called Ajv.

Security

Validating inputs has some security advantages. It can prevent bad or malicious data from being accepted by your API. For instance, you can specify that a certain field must be an integer, or that a string must match a certain regex pattern. This can help prevent SQL injection, cross-site scripting (XSS).

Defining a schema for your response types can help to prevent leaking sensitive data from your database. Your web server can be configured to not include any data that is not defined in the schema from your responses.

Performance

By validating data at the schema level, you can reject invalid requests early, before they reach more resource-intensive parts of your application. This can help protect against Denial of Service (DoS) attacks.

fast-json-stringify is a library that creates optimized stringify functions from JSON schemas that can help improve response times and throughput for JSON API’s.

Documentation

JSON Schema also greatly aids in API documentation. Tools like OpenAPI and Swagger use JSON Schema to automatically generate human-readable API documentation. This documentation provides developers with clear, precise information about your API’s endpoints, request parameters, and response formats. This not only helps to maintain consistent and clear communication within your development team, but also makes your API more accessible to outside developers.

Type-safety

I plan to cover this in more detail in an upcoming post but there are tools available that can help achieve type-safety both on your server and client-side by pairing JSON Schema with TypeScript. In Fastify for example, you can infer types in your request handlers based on your JSON Schema specifications.

Schema Examples

I’ve taken some example schemas from the Fastify website to walk through how they would work in practice.

### queryStringJsonSchema
const queryStringJsonSchema = {
  type: 'object',
   properties: {
     name: { type: 'string' },
     excitement: { type: 'integer' }
   }, 
  additionalProperites: "false"
}

We would use this schema to define, validate, and parse the query string of an incoming request in our API.

Given a query string like: ?name=Dane&excitement=10&other=additional - we can expect to receive an object that looks like this:

{
  name: "Dane",
  excitement: 10
}

Since additionalProperties are not allowed, the other property that wasn’t defined on our schema gets parsed out.

### paramsJsonSchema

Imagining we had a route in our API defined like /users/:userId/posts/:slug

const paramsJsonSchema = {
  type: 'object',
  properties: {
     userId: { type: 'number' },
     slug: { type: 'string' }
   },
 additionalProperties: "false",
 required: ["userId", "slug"]
}

Given this url: /users/1/posts/hello-world - we can expect to get an object in our handler that looks like this:

{
  userId: 1,
  slug: "hello-world"
}

We can be sure about this since the schema doesn’t allow for additional properties and both properties are required. If either field was missing or not matching its type, our API can automatically return a proper error response code.

Just to highlight what we are getting here again. We are able to provide fine-grained schema definitions for all the inputs and outputs of our API. Aside from serving as documentation and specification, it powers validation, parsing, and sanitizing values. I’ve found this to be a very simple and powerful tool in my toolbox.

Summary

In this post, we've explored the power and functionality of JSON Schema, a tool that often doesn't get the spotlight it deserves. We've seen how it provides a robust structure for JSON data, ensuring consistency, validity, and interoperability on a large scale. Through our user schema example, we've delved into key features like types, formats, and the ability to structure schemas using references, keeping our code DRY. We've also discussed the substantial benefits of using JSON Schema, such as validation, enhanced security, improved performance, and the potential for type-safety. We've touched on useful libraries like Ajv for validation and fast-json-stringify for performance optimization.

In a future post we will explore how we can utilize JSON Schema to achieve end-to-end type-safety in our applications.

About the author

Dane Grant

Dane Grant

Senior Software Engineer

JavaScript developer building things on web, native, and server environments. Free time filled with reading, cooking, dog, sports, comedy, and music.

Keep reading

View all posts →

End-to-end type-safety with JSON Schema

The article explores end-to-end type safety in JSON APIs using JSON Schema and TypeScript. It delves into methods such as generating types from schema definitions and utilizing TypeBox, data validation of serialized JSON data....

Dane Grant6 mins
JSONTypeScript

This Dot AI Field Notes - Anatomy of a Coding Harness

A coding agent is not magic, it’s a loop. We call this a harness. The harness is a deterministic layer of code that wraps an LLM....

1 min
AI

AI Is Speeding Up Development. But Where Are the New Bottlenecks?

AI is accelerating development, but it’s also exposing everything else that’s broken. At the Leadership Exchange, leaders unpacked how AI is reshaping the SDLC and what organizations need to address beyond just coding to make adoption successful. Moderated by Rob Ocel, VP of Innovation at This Dot Labs, the panel featured Itai Gerchikov at Anthropic and Harald Kirschner, Principal Product Manager for GitHub Copilot & VS Code at Microsoft. Panelists explored the current state of AI adoption across the software development lifecycle and shared practical insights into how organizations can effectively integrate AI tools. Panelists discussed how companies are investing in AI tools, skills, and managed competency programs to support developers. While AI can dramatically accelerate coding, the panel emphasized that adoption affects every stage of the SDLC. Bottlenecks now appear in testing, DevOps, product delivery, and marketing as AI speeds up development. Organizations that address technical debt and process inefficiencies are better positioned to extract maximum value from AI tools. The conversation also focused on opportunities and risks. Security, governance, and workforce education were highlighted as critical factors for adoption. Panelists stressed that AI initiatives should be aligned with broader business goals rather than pursued in isolation. They noted that companies experimenting at the cutting edge need to consider organizational readiness just as carefully as technical capabilities. Panelists also explored how leading organizations are navigating the early stages of adoption. Those ahead of the curve are using structured experimentation, prioritizing process improvements, and continuously evaluating outcomes to refine their AI strategies. Learning from these early adopters allows other organizations to anticipate emerging trends and prepare for the next phase of AI adoption rather than simply replicating past approaches. Key Takeaways Investing in AI skills and tools should be done thoughtfully, with clear alignment to business objectives. Examining the full SDLC helps identify bottlenecks that AI may accelerate or expose. Organizations can gain a competitive advantage by learning from early adopters and planning for where AI adoption is heading. AI adoption is not just a technical initiative; it is a strategic transformation that requires attention to people, process, and technology. Organizations that balance innovation with operational discipline will be best positioned to capture the full potential of AI across the software lifecycle. Seeing similar challenges in your own SDLC? Let’s compare notes. Join us at an upcoming Leadership Exchange or reach out to continue the conversation. Tracy can be reached at tlee@thisdot.co....

Calypso Hernandez2 mins
AI AdoptionAILeadership ExchangeEngineering Leadership

Making AI Deliver: From Pilots to Measurable Business Impact

A lot of organizations have experimented with AI, but far fewer are seeing real business results. At the Leadership Exchange, this panel focused on what it actually takes to move beyond experimentation and turn AI into measurable ROI. Over the past few years, many organizations have experimented with AI, but the challenge today is translating experimentation into measurable business value. Moderated by Tracy Lee, CEO at This Dot Labs, panelists featured Dorren Schmitt, Vice President IT Strategy & Innovation at Allen Media Group, Greg Geodakyan, CTO at Client Command, and Elliott Fouts, CAIO & CTO at This Dot Labs. Panelists discussed how companies are moving from early AI experiments to initiatives that deliver real results. They began by examining how experimentation has evolved over the past year. While many organizations did not fully utilize AI experimentation budgets in 2025, 2026 is showing a shift toward more intentional investment. Structured budgets and clearly defined frameworks are enabling companies to explore AI strategically and identify initiatives with high potential impact. The conversation then turned to alignment and ROI. Panelists highlighted the importance of connecting AI projects to corporate strategy and leadership priorities. Ensuring that AI initiatives translate into operational efficiency, productivity gains, and measurable business impact is essential. Companies that successfully align AI efforts with organizational goals are better equipped to demonstrate tangible outcomes from their investments. Moving from pilots and proofs of concept to production was another major focus. Governance, prioritization, and workflow integration were cited as essential for scaling AI initiatives. One panelist shared that out of nine proofs of concept, eight successfully launched, resulting in improvements in quality and operational efficiency. Panelists also explored the future of AI within organizations, including the potential for agentic workflows and reduced human in the loop processes. New capabilities are emerging that extend beyond coding tasks, reshaping how teams collaborate and how work is structured across departments. Key Takeaways Structured experimentation and defined budgets allow organizations to explore AI strategically and safely. Alignment with business priorities is essential for translating AI capabilities into measurable outcomes. Governance and workflow integration are critical to moving AI initiatives from pilot stages to production deployment. Successfully leveraging AI requires a balance between experimentation, strategic alignment, and operational discipline. Organizations that approach AI as a structured, measurable initiative can capture meaningful results and unlock new opportunities for innovation. Curious how your organization can move from AI experimentation to real impact? Let’s talk. Reach out to continue the conversation or join us at an upcoming Leadership Exchange. Tracy can be reached at tlee@thisdot.co....

Calypso Hernandez2 mins
AI AdoptionAILeadership ExchangeEngineering Leadership