Search⌘ K
AI Features

Extracting Out a Generic http Function

Explore how to implement a generic HTTP function that centralizes all REST API calls using fetch. Understand how to handle different request types, process JSON responses, and log errors. This lesson helps you write cleaner API interaction code and improves error handling for your React and ASP.NET Core web apps.

We'll need to use the fetch function in every function that needs to interact with the REST API. So, we are going to create a generic http function that we'll use to make all of our HTTP requests. This will nicely centralize the code that calls the REST API.

Steps to centralize the code that calls the REST API

Let's carry out the following steps:

  1. Create a new file called http.ts with the following content:

C#
import { webAPIUrl } from './AppSettings';
export interface HttpRequest<REQB> {
path: string;
}
export interface HttpResponse<RESB> {
ok: boolean;
body?: RESB;
}

We've started by importing the root path to our REST API from AppSettings.ts, which was set up in our starter project. The AppSettings.ts file is where we will build all of the different paths that will vary between development and production. Make sure ...