0
0
Rest APIprogramming~5 mins

Schema definitions in Rest API

Choose your learning style9 modes available
Introduction

Schema definitions help describe the shape and rules of data sent or received in an API. They make sure data is correct and easy to understand.

When you want to check that data sent to your API is complete and correct.
When you want to explain to others what data your API expects or returns.
When you want to automatically generate documentation for your API.
When you want to validate user input before saving it to a database.
When you want to avoid errors caused by missing or wrong data.
Syntax
Rest API
{
  "type": "object",
  "properties": {
    "fieldName": { "type": "string" },
    "age": { "type": "integer" }
  },
  "required": ["fieldName"]
}

Schema definitions often use JSON Schema format to describe data.

"type" defines the kind of data (string, integer, object, array, etc.).

Examples
This schema defines an object with a required "name" string and an optional "email" string.
Rest API
{
  "type": "object",
  "properties": {
    "name": { "type": "string" },
    "email": { "type": "string" }
  },
  "required": ["name"]
}
This schema defines an array where every item must be an integer.
Rest API
{
  "type": "array",
  "items": { "type": "integer" }
}
This schema defines an object with required "id" and "age" fields, where "age" must be zero or more.
Rest API
{
  "type": "object",
  "properties": {
    "id": { "type": "string" },
    "age": { "type": "integer", "minimum": 0 }
  },
  "required": ["id", "age"]
}
Sample Program

This program defines a schema for user data and checks if the sample data matches it. It prints a message if the data is valid or shows an error if not.

Rest API
import json
from jsonschema import validate, ValidationError

# Define a schema for user data
user_schema = {
    "type": "object",
    "properties": {
        "username": {"type": "string"},
        "email": {"type": "string"},
        "age": {"type": "integer", "minimum": 0}
    },
    "required": ["username", "email"]
}

# Sample data to validate
user_data = {
    "username": "alice",
    "email": "alice@example.com",
    "age": 30
}

try:
    validate(instance=user_data, schema=user_schema)
    print("User data is valid.")
except ValidationError as e:
    print(f"Validation error: {e.message}")
OutputSuccess
Important Notes

Always include required fields in your schema to avoid missing important data.

Use constraints like "minimum" or "maxLength" to make data more precise.

Validation helps catch errors early before processing data.

Summary

Schema definitions describe the expected data format for APIs.

They help validate data and improve API reliability.

Using schemas makes your API easier to understand and use.