Create Freestyle Fetch
Getting Started
Install and use the CLI to create type-safe API clients.
Installation
- Install the
create-freestyle-fetchpackage in your project:
npm install --save-dev create-freestyle-fetch- Or use it directly with
npxwithout installation:
npx create-freestyle-fetch generate --input ./spec.yaml --output ./src/apiPrerequisites
Before using the OpenAPI Generator, ensure you have:
- Node.js >= 18.0.0 installed on your system
- An Open API >= 3.0 specification file (
JSONorYAMLformat supported.) - The @freestylejs/fetch library installed in your project (added automatically as a dependency)
Basic Usage
A. Generate Your First Client
Create an API client from your OpenAPI specification:
npx create-freestyle-fetch generate \
--input ./openapi.yaml \
--output ./src/generatedThis command generates three files in the output directory:
models.ts- Zod schemas for all data typesapi.ts- Type-safe router with all API endpointsauth.ts- Authentication configuration and middlewareindex.ts- Re-exports for convenient imports
B. Use the Generated Client
Import and use the generated API client in your application. The generated code exports a createClient function that you can use to initialize the client with your base URL and authentication.
import { createClient } from './generated'
// Initialize the client
const client = createClient({
baseUrl: 'https://api.example.com',
auth: {
bearerAuth: { token: 'my-token' }
}
})
// GET request with path parameters
const user = await client.users.$userId.GET({
params: { userId: '123' }
})
// POST request with request body
const newPost = await client.posts.POST({
body: {
title: 'Hello World',
content: 'This is my first post'
}
})
// GET request with query parameters
const posts = await client.posts.GET({
query: {
page: 1,
limit: 10,
sort: 'created_at'
}
})Project Structure
After generation, your project will have:
your-project/
├── src/
│ ├── generated/
│ │ ├── models.ts # Zod schemas
│ │ ├── api.ts # API router
│ │ ├── auth.ts # Auth middleware
│ │ └── index.ts # Exports
│ └── your-code.ts # Your application
└── openapi.yaml # API specificationNext Steps
- CLI Reference - Learn all CLI options
- Generated Code - Understand the output
- Validation - Use Zod validation