This repository demonstrates how to build a Fastify API in TypeScript, achieving input validation, OpenAPI documentation, and request typing all through the use of JSON Schema. By utilizing JSON Schema, you ensure data validation, generate OpenAPI documentation, and enforce TypeScript types in a seamless and unified manner.
To effectively use this repository, it is recommended that you have a basic understanding of the following:
- TypeScript: a typed programming language that builds on JavaScript
- Fastify: a fast web framework for Node.js, ideal for building APIs
- OpenAPI specification: a industry standard specification for building APIs
- JSON Schema: a vocabulary that allows you to validate, annotate, and define the structure of JSON data
- TS Type inference: a TypeScript feature that allows the compiler to infer types based on the context without explicit type annotations
- TS Structural typing: the TypeScript type system that determines type compatibility based on the structure of the types
- Node.js 20.x or higher
- Clone the repository
git clone https://github.com/polarity-dev/fastify-typed-api.git
cd fastify-typed-api
- Install dependencies
npm install
- Run the development server
npm run dev
The API exposes many routes that demonstrate the use of JSON Schema for input validation, OpenAPI documentation, and TypeScript type enforcement.
The following routes are available on http://localhost:8000
:
GET /
- Health check routeGET /docs
- OpenAPI web documentation with RedocGET /schema
- OpenAPI schemaGET /users
- Get all usersGET /users/:id
- Get a user by ID
The repository includes a script to generate an SDK based on the OpenAPI schema. To generate the SDK, run the following command:
npm run generate:sdk
This command generates the sdk file in sdk/api.ts
that contains all the routes and types defined in the OpenAPI schema.
The client used in the SDK is axios and can be configured in the sdk/client.ts
file.
To run the tests, use the following command:
npm test
These are key resources directly related to the technologies and tools used in this repository.