At Agira, Technology Simplified, Innovation Delivered, and Empowering Business is what we are passionate about. We always strive to build solutions that boost your productivity.

How To Consume Web API Using Angular

  • By Amit Kumar
  • January 3, 2020
  • 2497 Views

In this tutorial, I’m going to explain how we can use the Web APIs in the Angular application using HttpClient. Before we start the step by step process, Let’s understand API and why do we need them.

What is API?

API stands for Application Program Interface. It is medium or intermediate to make a connection between Frontend and Backend applications.

Why do we need to use Web API in Angular application?

Angular is a front-end application development platform, It doesn’t contain any kind of database or processing of data. To get that part done we need some backend or server-side application that can do the processing of data and can provide those data in the form of APIs.
Ruby On Rails, .NET, Node are some of the common frameworks used.
Let’s get started!

Also Read

Learn How: Create A PWA with Service Workers in Angular

Create an Angular Project using CLI

$ ng new web-api-in-angular-demo
This will prompt you some options like adding routing and stylesheet selection, you can select as per your need. Next, you can run your application by using the below command.
$ cd web-api-in-angular-demo
$ ng serve
Now you can open your browser and go to this URL – http://localhost:4200. You’ll now see your application running.

Getting the API endpoint

We will be using a sample API that provides all the country. For more details click here.

Add service file

In this file, we will configure the HttpClient.
Generate service file using CLI by below command,
$ ng generate service api
This will generate the service file in this location – src/app/api.service.ts. Before editing the service file, we have to import HttpClientModule inside src/app/app.module.ts

import { HttpClientModule } from '@angular/common/http';
@NgModule({
  declarations: [AppComponent],
  entryComponents: [],
  imports: [
    HttpClientModule,
  ],
})
export class AppModule {}

Now we have to inject HttpClient inside service file – src/app/api.service.ts

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Injectable({
  providedIn: 'root'
})
export class ApiService {
  constructor(private httpClient: HttpClient) { }
}

Add a method to get all the country data.

public getCountry(){
    return this.httpClient.get(‘https://restcountries.eu/rest/v2/all
’);
  }

We are done with the basic setup of HttpClient and service file. To Generate a component where we will list the API response data. Use the below CLI command to generate component
$ ng generate component countryList
This will generate a component for you in – src/app/country-list/. Once the component is generated we need to add the routing for that component.
Adding route
Edit and add below code in src/app/app-routing.module.ts

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 go to http://localhost:4200/country-list you can see countryList component will be loaded. Using the service file to call the API and getting the data in the component.
Open the component and add the below 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.css']
})
export class CountryListComponent implements OnInit {
  constructor(private apiService: ApiService) { }
}

Next, we will define a variable and a method that will call the service and get the data.

export class CountryListComponent implements OnInit {
  countryList;
  constructor(private apiService: ApiService) { }
  ngOnInit() {
    this.apiService.getCountry().subscribe((data)=>{
      console.log(data);
      this.contryList = data;
    });
  }
}

Save and run the application and check the log, you will be able to see the list of all countries. Let’s populate the received data into a template to give a good look.
Edit your template file and add this – src/app/country-list/country-list.component.html

<div *ngFor="let country of countryList">
  <h3>CountryName</h3><span>{{country.name}}</span>
  <h3>Capital</h3><span>{{country.capital}}</span>
</div>

This will list all the countries with their capital in the template. Now, you can consume the Web API using Angular.
Got some good ideas? Then, you can try yourself. Feel free to comment on your doubts and suggestions we will get back to you. If you like such content, subscribe to our exclusive newsletter and get all the noteworthy updates on development technologies.

Looking for an Angular developer for your project? Get started by hiring our highly skilled Angular developer today!

Turn your vision to magnificent reality With
Our Web and Mobile Solutions

Amit Kumar

Amit Kumar | Software Engineer | Blockchain Developer | Blogger | at Agira Technologies, With 2 years of experience in Web Development & strong expertise in Ruby On Rails, AngularJS, CMS he is working around diverse projects & a perfect wanderer perceiving peace in traveling.