Skip to main content
Login Register
Code2night
  • Home
  • Blog Archive
  • Learn
    • Tutorials
    • Videos
  • Interview Q&A
  • Languages
    • Angular Angular js ASP.NET Asp.net Core ASP.NET Core, C# C C# C#, ASP.NET Core, Dapper
      C#, ASP.NET Core, Dapper, Entity Framework DotNet HTML/CSS Java JavaScript Node.js Python Python 3.11, Pandas, SQL
      Python 3.11, SQL Python 3.11, SQLAlchemy Python 3.11, SQLAlchemy, SQL Python 3.11, SQLite React Security SQL Server TypeScript
  • Post Blog
  • Tools
    • Beautifiers
      JSON Beautifier HTML Beautifier XML Beautifier CSS Beautifier JS Beautifier SQL Formatter
      Dev Utilities
      JWT Decoder Regex Tester Diff Checker Cron Explainer String Escape Hash Generator Password Generator
      Converters
      Base64 Encode/Decode URL Encoder/Decoder JSON to CSV CSV to JSON JSON to TypeScript Markdown to HTML Number Base Converter Timestamp Converter Case Converter
      Generators
      UUID / GUID Generator Lorem Ipsum QR Code Generator Meta Tag Generator
      Image Tools
      Image Converter Image Resizer Image Compressor Image to Base64 PNG to ICO Background Remover Color Picker
      Text & Content
      Word Counter PDF Editor
      SEO & Web
      SEO Analyzer URL Checker World Clock
  1. Home
  2. Blog
  3. Angular
  4. How To Consume Web API Using Angular

How To Consume Web API Using Angular

Date- May 10,2023 Updated Mar 2026 4025 Free Download Pay & Download
Angular API angular get api

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-angular

This 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 --open

Your 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 api

This 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 countryList

This 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.

How To Consume Web API Using Angular

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.

S
Shubham Batra
Programming author at Code2Night — sharing tutorials on ASP.NET, C#, and more.
View all posts →

Related Articles

Tag or mention people like WhatsApp & Skype by using @ in Angular
Jan 16, 2022
How to Apply css on child components in Angular
Jan 16, 2022
Export to Excel in Angular using ExcelJS?
Apr 13, 2023
Angular Material Select Dropdown with Image
Dec 13, 2022
Previous in Angular
Export to Excel in Angular using ExcelJS?
Next in Angular
Mastering Reactive Forms in Angular: A Comprehensive Guide
Buy me a pizza

Comments

On this page

More in Angular

  • Mastering Angular Directives: ngIf, ngFor, and ngSwitch Expl… 52 views
  • Mastering Angular Unit Testing with Jasmine and Karma: A Com… 48 views
  • Mastering HTTP Client in Angular: A Comprehensive Guide to R… 41 views
  • Mastering HTTP Interceptors in Angular for Enhanced API Comm… 39 views
  • Mastering Route Guards in Angular: Understanding CanActivate… 39 views
View all Angular posts →

Tags

AspNet C# programming AspNet MVC c programming AspNet Core C software development tutorial MVC memory management Paypal coding coding best practices data structures programming tutorial tutorials object oriented programming Slick Slider StripeNet
Free Download for Youtube Subscribers!

First click on Subscribe Now and then subscribe the channel and come back here.
Then Click on "Verify and Download" button for download link

Subscribe Now | 1770
Download
Support Us....!

Please Subscribe to support us

Thank you for Downloading....!

Please Subscribe to support us

Continue with Downloading
Be a Member
Join Us On Whatsapp
Code2Night

A community platform for sharing programming knowledge, tutorials, and blogs. Learn, write, and grow with developers worldwide.

Panipat, Haryana, India
info@code2night.com
Quick Links
  • Home
  • Blog Archive
  • Tutorials
  • About Us
  • Contact
  • Privacy Policy
  • Terms & Conditions
  • Guest Posts
  • SEO Analyzer
Dev Tools
  • JSON Beautifier
  • HTML Beautifier
  • CSS Beautifier
  • JS Beautifier
  • SQL Formatter
  • Diff Checker
  • Regex Tester
  • Markdown to HTML
  • Word Counter
More Tools
  • Password Generator
  • QR Code Generator
  • Hash Generator
  • Base64 Encoder
  • JWT Decoder
  • UUID Generator
  • Image Converter
  • PNG to ICO
  • SEO Analyzer
By Language
  • Angular
  • Angular js
  • ASP.NET
  • Asp.net Core
  • ASP.NET Core, C#
  • C
  • C#
  • C#, ASP.NET Core, Dapper
  • C#, ASP.NET Core, Dapper, Entity Framework
  • DotNet
  • HTML/CSS
  • Java
  • JavaScript
  • Node.js
  • Python
  • Python 3.11, Pandas, SQL
  • Python 3.11, SQL
  • Python 3.11, SQLAlchemy
  • Python 3.11, SQLAlchemy, SQL
  • Python 3.11, SQLite
  • React
  • Security
  • SQL Server
  • TypeScript
© 2026 Code2Night. All Rights Reserved.
Made with for developers  |  Privacy  ·  Terms
Translate Page
We use cookies to improve your experience and analyze site traffic. By clicking Accept, you consent to our use of cookies. Privacy Policy
Accessibility
Text size
High contrast
Grayscale
Dyslexia font
Highlight links
Pause animations
Large cursor