> For the complete documentation index, see [llms.txt](https://tech.x2bee.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://tech.x2bee.com/dev-guide/developer-guide-en/pjt-prepare/publish-your-docs/store-front-framework-next.js/04.-data-fetching/2.-basic-usage-of-restapiutil.md).

# 2. Basic Usage of RestApiUtil

This document explains how to fetch data using the RestApiUtil provided by the x2bee-core package.

x2bee-core includes RestApiUtil.

This restApiUtil is a util class that extends the basic fetch API to make up for the following shortcomings:

{% stepper %}
{% step %}

### Feature: Request / Response Interceptors

Supports the request interceptor and response interceptor features provided by axios.
{% endstep %}

{% step %}

### Feature: Automatic Serialization/Deserialization

Eliminates the hassle of having to manually serialize/deserialize text, blob, json, and other formats when returning body or response data.
{% endstep %}

{% step %}

### Feature: Base URL Configuration

Supports setting a base URL.
{% endstep %}

{% step %}

### Feature: Query Params Support

Lets you set params (query) data in addition to the body.
{% endstep %}

{% step %}

### Feature: Common Response Format

Consistently returns result data wrapped in a common ResponseDTO object.
{% endstep %}
{% endstepper %}

***

## 1. Server Component Example

```javascript
import { COMMON } from '@/constants/x2beeConstants';
import { restApiUtil } from 'x2bee-core';

const Home = async () => {
  const response = await restApiUtil
    .get(COMMON.API_URL + '/api/display/v1/shop/1?dispMediaCd=20');

  console.log(response);

  return (
    <div>
      <h1>Home</h1>
    </div>
  );
};

export default Home;
```

<figure><img src="https://200425-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FVEZx3rsZsIv89GPS3d2J%2Fuploads%2FyAoxFk3Fv60r4YFZBaQy%2Fimg%20(4).png?alt=media&#x26;token=cca60536-41e4-4063-a72f-e4ab2b7917ab" alt=""><figcaption></figcaption></figure>

By default, the result is returned as a ResponseEntity object.

Example: if you only want to use the payload

```javascript
import { COMMON } from '@/constants/x2beeConstants';
import { restApiUtil } from 'x2bee-core';

const Home = async () => {
  const data = await restApiUtil
    .get(COMMON.API_URL + '/api/display/v1/shop/1?dispMediaCd=20')
    .then(response => {
      return response.payload;
    })
    .catch(errorResponse => {
      return errorResponse.payload;
    });

  console.log(data);

  return (
    <div>
      <h1>Home</h1>
    </div>
  );
};

export default Home;
```

<figure><img src="https://200425-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FVEZx3rsZsIv89GPS3d2J%2Fuploads%2FG68U0mO3XVRgfoacQ6vu%2Fimg%20(5).png?alt=media&#x26;token=be910947-7c5a-414a-97d3-da5012f17c16" alt=""><figcaption></figcaption></figure>

This is an example of returning only the payload data in the then and catch clauses.

***

## 2. Client Component Example

```javascript
'use client';
import { COMMON } from '@/constants/x2beeConstants';
import { restApiUtil } from 'x2bee-core';

const Home = async () => {
  async function searchData() {
    const data = await restApiUtil
      .get(COMMON.API_URL + '/api/display/v1/shop/1?dispMediaCd=20')
      .then(response => {
        return response.payload;
      })
      .catch(errorResponse => {
        return errorResponse.payload;
      });

    console.log('버튼 클릭');
    console.log(data);
  }

  return (
    <div>
      <h1>Home</h1>
      <button onClick={searchData}>데이터 조회</button>
    </div>
  );
};

export default Home;
```

<figure><img src="https://200425-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FVEZx3rsZsIv89GPS3d2J%2Fuploads%2FXQ82qxTxPpn6lyrQSOwl%2Fimg%20(6).png?alt=media&#x26;token=667e704c-3965-42ed-b6d0-906c83a0dc84" alt=""><figcaption></figcaption></figure>

You can check the response data in the browser console when the button is clicked.

***

## 3. Functions Provided by restApiUtil

| Function               | Description                                                |
| ---------------------- | ---------------------------------------------------------- |
| restApiUtil.get()      | The GET method is mainly used to read or retrieve data     |
| restApiUtil.post()     | The POST method is mainly used to create a new resource    |
| restApiUtil.put()      | PUT is used to create/update a resource                    |
| restApiUtil.delete()   | The DELETE method is used to delete the specified resource |
| restApiUtil.formPost() | POST method for file uploads                               |
| restApiUtil.formPut()  | PUT method for file uploads                                |

***

## 4. restApiUtil Parameters

| Name                 | Description                                                                         |
| -------------------- | ----------------------------------------------------------------------------------- |
| url                  | The request URL                                                                     |
| options.baseUrl      | The default URL for the request                                                     |
| options.cache        | Whether to use cache. Default is no-store; use force-cache when caching is desired  |
| options.headers      | Request headers                                                                     |
| options.params       | Request parameters (query). When set, the values are appended to the end of the URL |
| options.body         | Request data                                                                        |
| options.interceptors | Provides request and response functions                                             |

Example:

```javascript
const response = await restApiUtil.get('/samples/nuxt1', {
  baseUrl: 'http://localhost:8888/api/sample',
  headers: {
    aaa1: 'testHeader1',
    aaa2: 'testHeader2',
    Cookie: 'bbb1=c1; bbb2=c2',
    Authorization: 'Bearer testToken99',
  },
  params: {
    test1: 'aaa',
    test2: 'bbb',
  },
  body: {
    log: 'value1',
    testValue: 'value2',
  },
  interceptors: {
    request: async (args) => {
      // 로딩바 생성
      args[0] = '/samples/test2'
      args[1].params.test2 = 'bbbb2';
      args[1].headers.aaa2 = 'testHeader2222';
      args[1].headers.Authorization = 'Bearer testToken88';
      return args;
    },
    response: async (response) => {
      // 로딩바 삭제
      if (response.status === 400) {
        return { test: '변경' };
      } else {
        return response;
      }
    },
  },
});
```

restApiUtil is a JavaScript util class that extends the pure fetch function and can be used in any JavaScript environment, such as next.js or nuxt.js. x2bee additionally provides a RestApi util that wraps this function specifically for next.js.
