Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Docs - Remove references to RadfishAPIService #48

Merged
merged 1 commit into from
Sep 4, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
229 changes: 166 additions & 63 deletions docs/building-your-application/patterns/apiservice.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,49 +4,76 @@ sidebar_position: 3

# Integrating with Backend Services

The **`RadfishAPIService`** is a class designed to facilitate interactions with a backend API. It simplifies making HTTP requests (GET, POST, PUT, DELETE) by encapsulating them into easy-to-use class methods. This service handles the construction of requests, including headers and query parameters, and processes responses.
You are free to use any network library of your choice to handle HTTP requests (GET, POST, PUT, DELETE). For your convenience, we’ve provided examples using the native fetch API. You can adapt these examples to the library that best fits your needs.

### **Features**

- **Token-based Authentication**: Manages API authentication using an access token.
- **HTTP Request Methods**: Supports GET, POST, PUT, and DELETE requests.
- **Error Handling**: Captures and returns error responses from an API.

### Why Use It

- **Simplification**: Abstracts the complexity of making HTTP requests and handling responses.
- **Reusability**: Can be easily reused across different components or services in your application.
- **Consistency**: Provides a consistent way to handle API requests and responses.
- **Error Handling**: Centralizes error handling logic, making it easier to manage.

### Usage

**Initializing the Service**
**Making API Requests**

To use **`RadfishAPIService`**, instantiate it with an access token:
A common pattern, is to call network requests in a `useEffect` that will trigger whenever a React component loads:

```jsx
import RadfishAPIService from "./RadfishAPIService";

const ApiService = new RadfishAPIService("your_access_token_here");
useEffect(() => {
async function fetchData() {
try {
const response = await fetch("https://api.example.com/data", {
headers: {
"X-Access-Token": "your-access-token",
},
});
if (!response.ok) {
throw new Error("Network response was not ok");
}
const data = await response.json();
console.log(data);
} catch (error) {
console.error("Error:", error);
}
}

fetchData();
}, []);
```

**Making API Requests**

- **`GET` Request**

- Asynchronous function to perform a `GET` request
- `@param {string} endpoint` - The API endpoint to perform the GET request.
- `@param {Object} queryParams` - The query parameters for the GET request.
- `@returns {Promise<Object|string>}` - A promise that resolves to the API response data or an error string.

```jsx
const getData = async (endpoint, queryParams) => {
return await ApiService.get(endpoint, queryParam);
};

getData("https://api.example.com/data", { param1: "a" });
```
```js
async function get(API_ENDPOINT, queryParams) {
const queryString = new URLSearchParams(queryParams).toString();
const url = `${endpoint}?${queryString}`;

try {
const response = await fetch(url, {
headers: {
"X-Access-Token": "your-access-token",
},
});
if (!response.ok) {
throw new Error("Network response was not ok");
}
const data = await response.json();
return data;
} catch (error) {
console.error("Error:", error);
throw error;
}
}

useEffect(() => {
const API_ENDPOINT = "https://api.example.com/data";
const params = { param1: "foo" };

const fetchData = async () => {
const data = await get(API_ENDPOINT, params);
// handle data as needed
};

fetchData();
}, []);
```

- **`POST` Request**

Expand All @@ -55,13 +82,41 @@ const ApiService = new RadfishAPIService("your_access_token_here");
- `@param {Object} body` - The request body for the POST request.
- `@returns {Promise<Object|string>}` - A promise that resolves to the API response data or an error string.

```jsx
const postData = async (endpoint, body) => {
return await ApiService.get(endpoint, body);
};

postData("https://api.example.com/data", { name: "foo" });
```
```jsx
async function post(API_ENDPOINT, bodyData) {
try {
const response = await fetch(API_ENDPOINT, {
method: "POST",
headers: {
"Content-Type": "application/json",
"X-Access-Token": "your-access-token",
},
body: JSON.stringify({ ...bodyData }),
});
if (!response.ok) {
throw new Error("Network response was not ok");
}
const data = await response.json();
return { data };
} catch (error) {
console.error("Error:", error);
throw error;
}
}

// Example usage
useEffect(() => {
const API_ENDPOINT = "https://api.example.com/data";
const bodyData = { key: "value" };

const postData = async () => {
const data = await post(API_ENDPOINT, bodyData);
// handle data as needed
};

postData();
}, []);
```

- **`PUT` Request**

Expand All @@ -70,13 +125,47 @@ const ApiService = new RadfishAPIService("your_access_token_here");
- `@param {Object} body` - The request body for the PUT request.
- `@returns {Promise<Object|string>}` - A promise that resolves to the API response data or an error string.

```jsx
const updateData = async (endpoint, body) => {
return await ApiService.get(endpoint, body);
};

putData("https://api.example.com/data", { name: "bar" });
```
```jsx
async function update(endpoint, { id, bodyData }) {
const url = `${endpoint}/${id}`;

try {
const response = await fetch(url, {
method: "PUT",
headers: {
"Content-Type": "application/json",
"X-Access-Token": "your-access-token",
},
body: JSON.stringify(bodyData),
});
if (!response.ok) {
throw new Error("Network response was not ok");
}
const data = await response.json();
return data;
} catch (error) {
console.error("Error:", error);
throw error;
}
}

useEffect(() => {
const API_ENDPOINT = "https://api.example.com/data";
const params = { id: 1, bodyData: { key: "updatedValue" } };

const updateData = async () => {
try {
const data = await update(API_ENDPOINT, params);
// handle data as needed
console.log("PUT Request Data:", data);
} catch (error) {
console.error("Failed to update data:", error);
}
};

updateData();
}, []);
```

- **`DELETE` Request**

Expand All @@ -85,25 +174,39 @@ const ApiService = new RadfishAPIService("your_access_token_here");
- `@param {Object} body` - The request body for the DELETE request.
- `@returns {Promise<Object|string>}` - A promise that resolves to the API response data or an error string.

```jsx
const deleteData = async (endpoint, body) => {
return await ApiService.get(endpoint, body);
};

deleteData("https://api.example.com/data", { id: 1 });
```

### **Handling Responses and Errors**

Responses and errors from the API are returned as promises.

### **Additional Information**

- The **`processQueryParameters`** and **`setHeaders`** functions are utility functions used internally by **`RadfishAPIService`** to process query parameters and set request headers, respectively.
- Ensure that the access token provided to **`RadfishAPIService`** is valid and has the necessary permissions for the requests being made.

By using **`RadfishAPIService`**, developers can streamline API interactions, making their code more readable and maintainable while handling various aspects of HTTP communication in a centralized manner.

```jsx
async function remove(endpoint, { id }) {
const url = `${endpoint}/${id}`;

try {
const response = await fetch(url, {
method: "DELETE",
headers: {
"X-Access-Token": "your-access-token",
},
});
if (!response.ok) {
throw new Error("Network response was not ok");
}
console.log("Data deleted successfully");
} catch (error) {
console.error("Error:", error);
throw error;
}
}

useEffect(() => {
const API_ENDPOINT = "https://api.example.com/data";
const params = { id: 1 };

const deleteData = async () => {
await remove(API_ENDPOINT, params);
// handle success if needed
};

deleteData();
}, []);
```
---

# React Query
Expand Down