<commit_before>---
id: createApi
title: createApi
sidebar_label: createApi
hide_title: true
---

# `createApi`

The main point where you will define a service to use in your application.

## Parameters

`createApi` accepts a single configuration object parameter with the following options:

```ts no-transpile
  baseQuery(args: InternalQueryArgs, api: QueryApi): any;
  endpoints(build: EndpointBuilder<InternalQueryArgs, EntityTypes>): Definitions;
  entityTypes?: readonly EntityTypes[];
  reducerPath?: ReducerPath;
  serializeQueryArgs?: SerializeQueryArgs<InternalQueryArgs>;
  keepUnusedDataFor?: number;
```

**It returns:**

- [`reducerPath`](#reducerpath)
- [`reducer`](#reducer)
- [`middleware`](#middleware)
- [`endpoints`](#endpoints-returned-by-createapi)
  - **[endpointName]**
    - [`initiate`](#actions)
    - [`select`](#select)
    - [`useQuery or useMutation`](#hooks)
- [`internalActions`](#internalactions)
- [`util`](#util)
- [`injectEndpoints`](#injectendpoints)
- [`usePrefetch`](../concepts/prefetching#prefetching-with-react-hooks)
- [`Auto-generated hooks`](#auto-generated-hooks)

```ts title="All returned properties"
const api = createApi({
  baseQuery: fetchBaseQuery('/'),
  endpoints: (builder) => ({
    // ...
  }),
});

export const {
  reducerPath,
  reducer,
  middleware,
  endpoints,
  internalActions,
  util,
  injectEndpoints,
  usePrefetch,
  ...generatedHooks
} = api;
```

#### middleware

This is a standard redux middleware and is responsible for things like [polling](../concepts/polling), [garbage collection](#keepunuseddatafor) and a handful of other things. Make sure it's [included in your store](../introduction/quick-start#add-the-service-to-your-store).

#### reducer

A standard redux reducer that enables core functionality. Make sure it's [included in your store](../introduction/quick-start#add-the-service-to-your-store).

### `endpoints` returned by `createApi`

#### actions

React Hooks users will most likely never need to use these in most cases. These are redux action creators that you can `dispatch` with `useDispatch` or `store.dispatch()`.

:::note Usage of actions outside of React Hooks
When dispatching an action creator, you're responsible for storing a reference to the promise it returns in the event that you want to update that specific subscription. To get an idea of what that entails, see the [Svelte Example](../examples/svelte) or the [React Class Components Example](../examples/react-class-components)
:::

#### select

`select` is how you access your `query` or `mutation` data from the cache. If you're using Hooks, you don't have to worry about this in most cases. There are several ways to use them:

```js title="React Hooks"
const { data, status } = useSelector(api.getPosts.select());
```

```js title="Using connect from react-redux"
const mapStateToProps = (state) => ({
  data: api.getPosts.select()(state),
});
connect(null, mapStateToProps);
```

```js title="Svelte"
$: ({ data, status } = api.getPosts.select()($store));
```

#### hooks

Hooks are specifically for React Hooks users. Under each `api.endpoint.[endpointName]`, you will have `useQuery` or `useMutation` depending on the type. For example, if you had `getPosts` and `updatePost`, these options would be available:

```ts title="Hooks usage"
const { data } = api.endpoints.getPosts.useQuery();
const { data } = api.endpoints.updatePost.useMutation();

const { data } = api.useGetPostsQuery();
const [updatePost] = api.useUpdatePostMutation();
```

### `baseQuery`

```ts title="Simulating axios-like interceptors with a custom base query"
function baseQueryWithReauth(arg, api) {
  let result = fetchBaseQuery(arg, api);
  if (result.error && result.error.status === '401') {
    const refreshResult = fetchBaseQuery('/refreshToken');
    if (refreshResult.data) {
      dispatch(setToken(refreshResult.data));
      result = fetchBaseQuery(arg, api);
    } else {
      dispatch(loggedOut());
    }
  }
  return result;
}
```

### `entityTypes`
<commit_msg>Update docs/api/createApi.md<commit_after>---
id: createApi
title: createApi
sidebar_label: createApi
hide_title: true
---

# `createApi`

The main point where you will define a service to use in your application.

## Parameters

`createApi` accepts a single configuration object parameter with the following options:

```ts no-transpile
  baseQuery(args: InternalQueryArgs, api: QueryApi): any;
  endpoints(build: EndpointBuilder<InternalQueryArgs, EntityTypes>): Definitions;
  entityTypes?: readonly EntityTypes[];
  reducerPath?: ReducerPath;
  serializeQueryArgs?: SerializeQueryArgs<InternalQueryArgs>;
  keepUnusedDataFor?: number;
```

**It returns:**

- [`reducerPath`](#reducerpath)
- [`reducer`](#reducer)
- [`middleware`](#middleware)
- [`endpoints`](#endpoints-returned-by-createapi)
  - **[endpointName]**
    - [`initiate`](#actions)
    - [`select`](#select)
    - [`useQuery or useMutation`](#hooks)
- [`internalActions`](#internalactions)
- [`util`](#util)
- [`injectEndpoints`](#injectendpoints)
- [`usePrefetch`](../concepts/prefetching#prefetching-with-react-hooks)
- [`Auto-generated hooks`](#auto-generated-hooks)

```ts title="All returned properties"
const api = createApi({
  baseQuery: fetchBaseQuery('/'),
  endpoints: (builder) => ({
    // ...
  }),
});

export const {
  reducerPath,
  reducer,
  middleware,
  endpoints,
  internalActions,
  util,
  injectEndpoints,
  usePrefetch,
  ...generatedHooks
} = api;
```

#### middleware

This is a standard redux middleware and is responsible for things like [polling](../concepts/polling), [garbage collection](#keepunuseddatafor) and a handful of other things. Make sure it's [included in your store](../introduction/quick-start#add-the-service-to-your-store).

#### reducer

A standard redux reducer that enables core functionality. Make sure it's [included in your store](../introduction/quick-start#add-the-service-to-your-store).

### `endpoints` returned by `createApi`

#### actions

React Hooks users will most likely never need to use these in most cases. These are redux action creators that you can `dispatch` with `useDispatch` or `store.dispatch()`.

:::note Usage of actions outside of React Hooks
When dispatching an action creator, you're responsible for storing a reference to the promise it returns in the event that you want to update that specific subscription. To get an idea of what that entails, see the [Svelte Example](../examples/svelte) or the [React Class Components Example](../examples/react-class-components)
:::

#### select

`select` is how you access your `query` or `mutation` data from the cache. If you're using Hooks, you don't have to worry about this in most cases. There are several ways to use them:

```js title="React Hooks"
const { data, status } = useSelector(api.getPosts.select());
```

```js title="Using connect from react-redux"
const mapStateToProps = (state) => ({
  data: api.getPosts.select()(state),
});
connect(null, mapStateToProps);
```

```js title="Svelte"
$: ({ data, status } = api.getPosts.select()($store));
```

#### hooks

Hooks are specifically for React Hooks users. Under each `api.endpoint.[endpointName]`, you will have `useQuery` or `useMutation` depending on the type. For example, if you had `getPosts` and `updatePost`, these options would be available:

```ts title="Hooks usage"
const { data } = api.endpoints.getPosts.useQuery();
const { data } = api.endpoints.updatePost.useMutation();

const { data } = api.useGetPostsQuery();
const [updatePost] = api.useUpdatePostMutation();
```

### `baseQuery`

```ts title="Simulating axios-like interceptors with a custom base query"
const baseQuery = fetchBaseQuery({ baseUrl: '/' });

function baseQueryWithReauth(arg, api) {
  let result = baseQuery(arg, api);
  if (result.error && result.error.status === '401') {
    // try to get a new token
    const refreshResult = baseQuery('/refreshToken');
    if (refreshResult.data) {
      // store the new token
      dispatch(setToken(refreshResult.data));
      // retry the initial query
      result = baseQuery(arg, api);
    } else {
      dispatch(loggedOut());
    }
  }
  return result;
}
```

### `entityTypes`

{'fraction_non_alphanumeric': 0.14243866715488832, 'fraction_numerical': 0.0007323324789454412, 'mean_word_length': 4.750175438596491, 'pattern_counts': {'":': 0, '<': 7, '<?xml version=': 0, '>': 11, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '6398369', 'n_tokens_mistral': 2530, 'n_tokens_neox': 2432, 'n_words': 759}