Movatterモバイル変換


[0]ホーム

URL:


Host your specs. Generate from anywhere.Get started
Skip to content

Appearance

Fetch API

About

TheFetch API provides an interface for fetching resources (including across the network). It is a more powerful and flexible replacement for XMLHttpRequest.

The Fetch API client for Hey API generates a type-safe client from your OpenAPI spec, fully compatible with validators, transformers, and all core features.

Demo

Features

  • seamless integration with@hey-api/openapi-ts ecosystem
  • type-safe response data and errors
  • response data validation and transformation
  • access to the original request and response
  • granular request and response customization options
  • minimal learning curve thanks to extending the underlying technology
  • support bundling inside the generated output

Installation

In yourconfiguration, add@hey-api/client-fetch to your plugins and you'll be ready to generate client artifacts. 🎉

js
export default {  input:'hey-api/backend',// sign up at app.heyapi.dev  output:'src/client',  plugins: ['@hey-api/client-fetch'],};
sh
npx @hey-api/openapi-ts \  -i hey-api/backend \  -o src/client \  -c @hey-api/client-fetch

TIP

This step is optional because Fetch is the default client.

Configuration

The Fetch client is built as a thin wrapper on top of Fetch API, extending its functionality to work with Hey API. If you're already familiar with Fetch, configuring your client will feel like working directly with Fetch API.

When we installed the client above, it created aclient.gen.ts file. You will most likely want to configure the exportedclient instance. There are two ways to do that.

setConfig()

This is the simpler approach. You can call thesetConfig() method at the beginning of your application or anytime you need to update the client configuration. You can pass any Fetch API configuration option tosetConfig(), and even your ownFetch implementation.

js
import { client }from 'client/client.gen';client.setConfig({  baseUrl:'https://example.com',});

The disadvantage of this approach is that your code may call theclient instance before it's configured for the first time. Depending on your use case, you might need to use the second approach.

Runtime API

Sinceclient.gen.ts is a generated file, we can't directly modify it. Instead, we can tell our configuration to use a custom file implementing the Runtime API. We do that by specifying theruntimeConfigPath option.

js
export default {  input:'hey-api/backend',// sign up at app.heyapi.dev  output:'src/client',  plugins: [    {      name:'@hey-api/client-fetch',      runtimeConfigPath:'./src/hey-api.ts',    },  ],};

In our custom file, we need to export acreateClientConfig() method. This function is a simple wrapper allowing us to override configuration values.

ts
import type { CreateClientConfig }from './client/client.gen';export const createClientConfig: CreateClientConfig = (config)=> ({  ...config,  baseUrl:'https://example.com',});

With this approach,client.gen.ts will callcreateClientConfig() before initializing theclient instance. If needed, you can still usesetConfig() to update the client configuration later.

createClient()

You can also create your own client instance. You can use it to manually send requests or point it to a different domain.

js
import { createClient }from './client/client';const myClient = createClient({  baseUrl:'https://example.com',});

You can also pass this instance to any SDK function through theclient option. This will override the default instance fromclient.gen.ts.

js
const response = await getFoo({  client: myClient,});

SDKs

Alternatively, you can pass the client configuration options to each SDK function. This is useful if you don't want to create a client instance for one-off use cases.

js
const response = await getFoo({  baseUrl:'https://example.com',// <-- override default configuration});

Interceptors

Interceptors (middleware) can be used to modify requests before they're sent or responses before they're returned to your application.

They can be added withuse, removed witheject, and updated wthupdate. Theuse andupdate methods will return the ID of the interceptor for use witheject andupdate. Fetch API does not have the interceptor functionality, so we implement our own.

Example: Request interceptor

js
import { client }from 'client/client.gen';async function myInterceptor(request) {  // do something  return request;}interceptorId= client.interceptors.request.use(myInterceptor);
js
import { client }from 'client/client.gen';// eject by IDclient.interceptors.request.eject(interceptorId);// eject by referenceclient.interceptors.request.eject(myInterceptor);
js
import { client }from 'client/client.gen';async function myNewInterceptor(request) {  // do something  return request;}// update by IDclient.interceptors.request.update(interceptorId, myNewInterceptor);// update by referenceclient.interceptors.request.update(myInterceptor, myNewInterceptor);

Example: Response interceptor

js
import { client }from 'client/client.gen';async function myInterceptor(response) {  // do something  return response;}interceptorId= client.interceptors.response.use(myInterceptor);
js
import { client }from 'client/client.gen';// eject by IDclient.interceptors.response.eject(interceptorId);// eject by referenceclient.interceptors.response.eject(myInterceptor);
js
import { client }from 'client/client.gen';async function myNewInterceptor(response) {  // do something  return response;}// update by IDclient.interceptors.response.update(interceptorId, myNewInterceptor);// update by referenceclient.interceptors.response.update(myInterceptor, myNewInterceptor);

TIP

To eject, you must provide the ID or reference of the interceptor passed touse(), the ID is the value returned byuse() andupdate().

Auth

The SDKs include auth mechanisms for every endpoint. You will want to configure theauth field to pass the right token for each request. Theauth field can be a string or a function returning a string representing the token. The returned value will be attached only to requests that require auth.

js
import { client }from 'client/client.gen';client.setConfig({  auth: ()=> '<my_token>',  baseUrl:'https://example.com',});

If you're not using SDKs or generating auth, using interceptors is a common approach to configuring auth for each request.

js
import { client }from 'client/client.gen';client.interceptors.request.use((request,options)=> {  request.headers.set('Authorization','Bearer <my_token>');  return request;});

Build URL

If you need to access the compiled URL, you can use thebuildUrl() method. It's loosely typed by default to accept almost any value; in practice, you will want to pass a type hint.

ts
type FooData = {  path: {    fooId: number;  };  query?: {    bar?: string;  };  url: '/foo/{fooId}';};const url = client.buildUrl<FooData>({  path: {    fooId:1,  },  query: {    bar:'baz',  },  url:'/foo/{fooId}',});console.log(url);// prints '/foo/1?bar=baz'

Custom Instance

You can provide a customfetch instance. This is useful if you need to extend the default instance with extra functionality, or replace it altogether.

js
import { client }from 'client/client.gen';client.setConfig({  fetch: ()=> {    /* custom `fetch` method */  },});

You can use any of the approaches mentioned inConfiguration, depending on how granular you want your custom instance to be.

API

You can view the complete list of options in theUserConfig interface.

Examples

You can view live examples onStackBlitz.

Sponsors

Hey API is sponsor-funded. If you rely on Hey API in production, consider becoming asponsor to accelerate the roadmap.

Gold

Silver

Bronze

  • Kinde logo

Friends


[8]ページ先頭

©2009-2026 Movatter.jp