Calling REST APIs in Angular

This tutorial is designed to guide you through the process of calling REST APIs using Angular, providing you with practical examples of code along the way. By following this tutorial, you will gain a comprehensive understanding of how to effectively make REST APIs call within your Angular applications.

Angular provides HttpClient module from the @angular/common/http package for handling AJAX (Asynchronous JavaScript and XML) requests and interacting with RESTful APIs. HttpClient module simplifies the process of making HTTP calls, retrieving data, and sending data to RESTful services. It offers a variety of methods to perform different types of HTTP operations, such as GET, POST, PUT, DELETE, etc.

To call a REST API in Angular, you can follow these steps:

Importing provideHttpClient

Angular provides the provideHttpClient function, which is designed to configure the HttpClient service for injection. The HttpClient is a powerful tool for making HTTP requests. To use the HttpClient, provideHttpClient must be imported into your Angular application. When you import provideHttpClient and include provideHttpClient() in the list of providers, you are essentially informing Angular that your application will be using the HttpClient service. Angular will then set up the necessary infrastructure to allow you to inject the HttpClient service into your components, services, and other parts of your application.

By importing provideHttpClient in the app.config.ts file, you are configuring the HttpClient service globally for your entire application. This means you can use the HttpClient service in any component or service without having to import provideHttpClient again in those specific files.

Here's how you can import provideHttpClient in the src/app/app.config.ts file and include provideHttpClient() in the list of providers within app.config.ts file:

import { ApplicationConfig } from '@angular/core';
import { provideRouter } from '@angular/router';
import { routes } from './app.routes';
import { provideClientHydration } from '@angular/platform-browser';
import { provideHttpClient } from '@angular/common/http';

export const appConfig: ApplicationConfig = {
  providers: [
    provideRouter(routes),
    provideClientHydration(),
    provideHttpClient(),
  ],
};

Creating an API service

Create a service to handle API calls using the Angular CLI:

ng generate service services/api

This will create a file named api.service.ts in the src/app/services folder.

Implementing API service

Open the src/app/api.service.ts file and implement the service with the necessary methods for GET, POST, PUT, and DELETE requests along with headers:

import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class ApiService {
  private apiBaseUrl = 'http://localhost:8080'; // Example API URL, replace with your API URL

  constructor(private http: HttpClient) {}

  private httpOptions: Object = { 
    headers: new HttpHeaders({
      'Access-Control-Allow-Origin': '*',
      'ContentType': 'application/json'
    }),
  };
 
  // GET Request
  get(endpoint: string, options?: any): Observable<any> {
    if (!options) {
      options = this.httpOptions;
    }
    return this.http.get(`${this.apiBaseUrl}/${endpoint}`, options);
  }

  // POST Request
  post(endpoint: string, data: any, options?: any): Observable<any> {
    if (!options) {
      options = this.httpOptions;
    }
    return this.http.post(`${this.apiBaseUrl}/${endpoint}`, data, options);
  }

  // PUT Request
  put(endpoint: string, data: any, options?: any): Observable<any> {
    if (!options) {
      options = this.httpOptions;
    }
    return this.http.put(`${this.apiBaseUrl}/${endpoint}`, data, options);
  }

  // DELETE Request
  delete(endpoint: string, options?: any): Observable<any> {
    if (!options) {
      options = this.httpOptions;
    }
    return this.http.delete(`${this.apiBaseUrl}/${endpoint}`, options);
  }

}

Using the API service in a component

Open the src/app/your.component.ts file (For example, src/app/student-detail.component.ts) and use the ApiService to make API calls in the component:

import { Component, OnInit } from '@angular/core';
import { ApiService } from '../services/api.service';

@Component({
  selector: 'app-student-detail',
  standalone: true,
  imports: [],
  templateUrl: './student-detail.component.html',
  styleUrl: './student-detail.component.css',
})
export class StudentDetailComponent implements OnInit {
  constructor(private apiService: ApiService) {}

  ngOnInit(): void {}

  getStudents() {
    const studentId = 1; //Sending studentId as a path variable
    this.apiService.get('students/' + studentId).subscribe({
      next: (data) => {
        // Handle response
      },
      error: (err) => {
        console.log(err);
      },
      complete() {
        console.log('Complete...');
      },
    });
  }

  saveStudent() {
    const postData = { firstName: 'foo', lastName: 'bar', email: 'foo@example.com' };
    this.apiService.post('students/register', postData).subscribe({
      next: (data) => {
        // Handle response
      },
      error: (err) => {
        console.log(err);
      },
      complete() {
        console.log('Complete...');
      },
    });
  }

  updateStudent() {
    const putData = { id: 1, firstName: 'doo', lastName: 'car', email: 'doo@example.com'  };
    this.apiService.put('students/update', putData).subscribe({
      next: (data) => {
        // Handle response
      },
      error: (err) => {
        console.log(err);
      },
      complete() {
        console.log('Complete...');
      },
    });
  }

  deleteStudent() {
    const studentId = 1; //Sending studentId as a path variable
    this.apiService.delete('students/delete/' + studentId).subscribe({
      next: (data) => {
        // Handle response
      },
      error: (err) => {
        console.log(err);
      },
      complete() {
        console.log('Complete...');
      },
    });
  }

}

This is a basic example to get you started. Make sure to replace the API URL and adjust the endpoint names and data based on your API requirements.