Redux
Intermediate

API Slice Creation

Create an API slice with createApi and set up your base query and endpoints.

25 min
2 sections
createapi
apislice
endpoints
1
2

01. createApi Overview

Section 1 of 2

createApi is the core of RTK Query. It defines your API slice, base query, and endpoints in one place.

typescript
import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react';

export const api = createApi({
  reducerPath: 'api',
  baseQuery: fetchBaseQuery({ baseUrl: '/api' }),
  endpoints: (builder) => ({
    getTodos: builder.query<Todo[], void>({
      query: () => '/todos',
    }),
    addTodo: builder.mutation<Todo, Partial<Todo>>({
      query: (todo) => ({
        url: '/todos',
        method: 'POST',
        body: todo,
      }),
    }),
  }),
});

export const { useGetTodosQuery, useAddTodoMutation } = api;

Exercise

Create an API Slice

Practice

Create an API slice with endpoints for fetching posts and creating a new post.

Back to Course