Schema
A formal description of the structure, constraints, and relationships of data, used for validation, documentation, and type safety.
Detailed Explanation
A schema defines the shape of data: what fields exist, their types, which are required, and how they relate to other data structures. Schemas are used in: databases (table definitions), APIs (request/response formats), configuration files (validating settings), and data validation (ensuring data conforms to expected formats).
Schema tools: JSON Schema (validates JSON), GraphQL Schema (defines API types and operations), Prisma Schema (defines database models), and TypeScript types (compile-time type checking). Schemas serve as documentation, enable tooling (autocompletion, validation), and catch errors at development time.
Why It Matters
Schemas provide structure, validation, and documentation for data. They catch errors early, enable tooling, and serve as living documentation.
Real-World Example
A Prisma schema defines a User model with fields: id (Int, required), email (String, unique), name (String, optional), and posts (relation to Post). Prisma generates migrations, TypeScript types, and a query client from this schema.
When to Use
For all data structures: database models, API contracts, configuration files, and message formats. Schemas catch errors early and enable powerful tooling.
Advantages
- Catches errors at development time
- Enables autocompletion and tooling
- Serves as living documentation
- Enables data validation
- Improves code maintainability
Disadvantages
- Requires maintenance as data evolves
- Can be verbose for simple structures
- Schema changes require migration
- Learning curve for schema languages
- Overhead for rapid prototyping
Related Terms
Frequently Asked Questions
What is the difference between a schema and a type?
A schema is a formal data definition (validates at runtime). A type is a compile-time construct (TypeScript, Flow). Schemas validate external data; types ensure internal code consistency. Both define data shape.
What is JSON Schema?
JSON Schema is a vocabulary for validating JSON data. It defines expected structure, types, and constraints. Use it for API request/response validation, configuration validation, and test data generation.
How do schemas improve API design?
Schemas define the API contract: what endpoints exist, what they accept, and what they return. Tools like OpenAPI (Swagger) generate documentation, client SDKs, and server stubs from schemas.
What is schema-first vs code-first design?
Schema-first: define the schema (OpenAPI, GraphQL SDL) first, then generate code. Code-first: write code, then generate schema. Schema-first is better for API design; code-first is faster for rapid development.
How do I handle schema evolution?
Add new fields (non-breaking), deprecate old fields (mark as deprecated), and remove them later. Use versioning for breaking changes. For databases, use migration tools (Prisma Migrate, Flyway).