How To Consume Web API Using Angular
What is a Web API?
A Web API (Application Programming Interface) is a set of rules and protocols for building and interacting with software applications. It allows different systems to communicate over the internet, enabling data exchange and functionality sharing. In the context of web development, APIs often provide access to server resources, enabling developers to retrieve or send data.
Web APIs can be categorized into various types, including RESTful APIs, SOAP APIs, and GraphQL APIs. RESTful APIs are the most commonly used due to their simplicity and scalability, utilizing standard HTTP methods like GET, POST, PUT, and DELETE to perform operations on resources.
Why Use Angular for Consuming Web APIs?
Angular is a powerful front-end framework developed by Google, designed for building dynamic web applications. One of its core features is the ability to easily consume Web APIs using the HttpClient module. This module simplifies the process of making HTTP requests and handling responses, allowing developers to focus on building their applications rather than dealing with complex network operations.
Using Angular's HttpClient, developers can perform asynchronous requests, ensuring that the user interface remains responsive while waiting for data. Additionally, Angular provides built-in support for observables, making it easier to manage data streams and react to changes.
Prerequisites
Before diving into the implementation, ensure you have the following prerequisites:
- Node.js and npm installed on your machine.
- Basic knowledge of Angular and TypeScript.
- An understanding of RESTful APIs and HTTP methods.
Creating an Angular Project Using CLI
To start, we need to create a new Angular project. Use the Angular CLI (Command Line Interface) to generate your project:
$ ng new web-api-in-angularThis command will prompt you to select options like adding routing and choosing a stylesheet format. Select the options according to your preferences. After that, navigate to the project directory and run the application:
$ cd web-api-in-angular
$ ng serve --openYour application will automatically open in the browser at http://localhost:4200, displaying the default Angular welcome page.
Adding a Service File
Next, we need to create a service file to handle our API communications. Generate the service file using the Angular CLI:
$ ng generate service apiThis will create a service file located at src/app/api.service.ts. Before editing this file, we must import the HttpClientModule into our application module.
Open src/app/app.module.ts and add the necessary imports:
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { HttpClientModule } from '@angular/common/http';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { CountryListComponent } from './country-list/country-list.component';
@NgModule({
declarations: [
AppComponent,
CountryListComponent,
],
imports: [
BrowserModule,
AppRoutingModule,
HttpClientModule,
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }Injecting HttpClient into the Service
Now, we will inject the HttpClient into our service file to make API calls. Open src/app/api.service.ts and add the following code:
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Injectable({
providedIn: 'root'
})
export class ApiService {
constructor(private httpClient: HttpClient) { }
public getCountry() {
return this.httpClient.get('https://restcountries.com/v3.1/all');
}
}In this code, we create a method called getCountry that uses the HttpClient to fetch data from the REST Countries API, which provides information about countries.
Generating a Component to Display API Data
Next, we need a component where we can display the data retrieved from the API. Generate a new component using the CLI:
$ ng generate component countryListThis command will create a new component in src/app/country-list/. After generating the component, we need to set up routing for it.
Setting Up Routing for the Component
Edit src/app/app-routing.module.ts to add a route for the newly created component:
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { CountryListComponent } from './country-list/country-list.component';
const routes: Routes = [
{ path: 'country-list', component: CountryListComponent }
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }Now, navigate to http://localhost:4200/country-list to see the CountryListComponent loaded in your application.
Consuming the API in the Component
In the component, we will utilize the service to call the API and retrieve data. Open src/app/country-list/country-list.component.ts and add the following code:
import { Component, OnInit } from '@angular/core';
import { ApiService } from '../api.service';
@Component({
selector: 'app-country-list',
templateUrl: './country-list.component.html',
styleUrls: ['./country-list.component.scss']
})
export class CountryListComponent implements OnInit {
countryList: any;
constructor(private apiService: ApiService) { }
ngOnInit() {
this.apiService.getCountry().subscribe((data) => {
console.log(data);
this.countryList = data;
});
}
}In this code, we subscribe to the observable returned by the getCountry method. The data received from the API is logged to the console and assigned to the countryList property.
Displaying the Data in the Template
To present the data in a user-friendly format, edit the template file located at src/app/country-list/country-list.component.html and add the following code:
<div *ngFor="let country of countryList">
<div>
<h3 style="display: inline-block;padding: 0px 60px 0px 15px;">Country Name</h3><span>{{country.name.common}}</span>
<h3 style="display: inline-block;padding: 0px 60px 0px 150px;">Capital</h3><span>{{country.capital}}</span>
</div>
</div>This code iterates over the countryList array and displays the country name and capital for each entry. Save and run the application again using ng serve --open to view the results.

Edge Cases & Gotchas
While consuming Web APIs in Angular, there are several edge cases and potential pitfalls to be aware of:
- Handling Errors: Always implement error handling when making HTTP requests. Use the catchError operator from RxJS to manage errors gracefully.
- Unsubscribing: If you subscribe to an observable in a component, ensure you unsubscribe to prevent memory leaks, especially in components that may be destroyed.
- CORS Issues: Cross-Origin Resource Sharing (CORS) may block requests from your Angular app to a different domain. Make sure the API server allows your app's origin.
- Data Formats: APIs may return data in various formats. Ensure your application can handle unexpected data structures or types.
Performance & Best Practices
To enhance the performance and maintainability of your Angular application when consuming Web APIs, consider the following best practices:
- Use Environment Variables: Store API endpoints in environment files to manage different configurations for development and production.
- Optimize API Calls: Minimize the number of API calls by batching requests or caching responses when appropriate.
- Use Observables Effectively: Leverage RxJS operators like map, filter, and switchMap to transform and manage data streams efficiently.
- Implement Loading Indicators: Provide feedback to users by showing loading indicators while data is being fetched.
Conclusion
In this tutorial, we explored how to consume Web APIs using Angular's HttpClient. We covered the necessary steps from setting up a new Angular project to displaying API data in a component. Here are the key takeaways:
- Web APIs allow applications to interact with external data sources.
- Angular's HttpClient simplifies the process of making HTTP requests.
- Proper error handling and performance optimizations are crucial for a responsive application.
- Always be aware of edge cases and best practices when working with APIs.