How to Call APIs in Angular? (2024)

Calling APIs is a major part of any web application. Today, countless APIs are waiting to be consumed in meaningful applications, whether React, Vue, Svelte or Angular-based.

Angular

Angular, led by Google, is an open-source front-end framework. Focused on building user interfaces for web and mobile applications, it is among the most popular JavaScript frameworks for building applications.

Angular is built on TypeScript and offers a powerful CLI to develop Angular applications. With that said, let's see how we can call APIs in an Angular application. I have divided the process into steps which are as follows:

→ STEP 1: Find an API

First of all, let's find an API to use in our Go application. RapidAPI Hub enables you to choose from thousands of public APIs for use in your projects.

Loading component...

For this guide, we will use the Random Facts API from RapidAPI Hub that gives us the carbon footprint data of travel.

To use this API, you need to subscribe to it first. You can do this by clicking on the Subscribe to Test button, which will redirect you to the pricing page. You can select the free plan for this guide.

After all this, you will be redirected back to the original page. Here you will have a field named x-rapidapi-key. It is your API key. Save it somewhere because we will need it in the application later.

→ STEP 2: Create the application

We need the official Angular CLI to create a new Angular application and develop it. Run the following command in your terminal to install the CLI:

sh

npm install -g @angular/cli

Once installed, we can use the command ng to access the CLI. The following command will create a new application named api-angular.

sh

ng new api-angular

Once you are done, open this project in your preferred code editor.

→ STEP 3: Start the application

To run the app, open the terminal in the api-angular directory and run the following command:

sh

This command will serve your application, an2d you will be able to view the starter app by navigating to http://localhost:4200/.

→ STEP 4: Formulate the API Request

Now, let's get our hands dirty and start writing the code to consume the API. The first thing we need to do is to import the HttpClientModule, which allows us to make HTTP requests. So, go ahead and import it in your src/app/app.module.ts file.

ts

import {NgModule} from '@angular/core';

import {BrowserModule} from '@angular/platform-browser';

import {HttpClientModule} from '@angular/common/http'; // importing the http module

import {AppRoutingModule} from './app-routing.module';

import {AppComponent} from './app.component';

@NgModule({

declarations: [AppComponent],

imports: [

BrowserModule,

AppRoutingModule,

HttpClientModule // adding it in the imports

],

providers: [],

bootstrap: [AppComponent]

})

export class AppModule {}

Now, you can add the call to the API in any component of the application. Open the app.component.ts file, and import the HttpClient and HttpHeaders modules as follows:

ts

import {Component} from '@angular/core';

import {HttpClient, HttpHeaders} from '@angular/common/http';

@Component({

selector: 'app-root',

templateUrl: './app.component.html',

styleUrls: ['./app.component.css']

})

export class AppComponent {

constructor(private http: HttpClient) {}

title = 'api-angular';

}

Now, we will use the http.get method to send the request to the API. Our API call will look like this in code:

ts

let headers = new HttpHeaders({

'x-rapidapi-host': 'random-facts2.p.rapidapi.com',

'x-rapidapi-key': 'your-api-key'

});

this.http

.get<any>('https://random-facts2.p.rapidapi.com/getfact', {

headers: headers

})

.subscribe(data => {

console.log(data);

});

Notice how we added the headers, including our RapidAPI key. Replace the value of the x-rapidapi-key in the above code snippet with the API key you saved earlier.

→ FINAL STEP: The API response

Finally, we can wrap the API call in the ngOnInit() method, a lifecycle hook in Angular which is fired whenever a component finishes loading. After adding the API call in the hook, the ngOnInit hook will trigger the API call whenever the component loads. The final code looks like this:

ts

//app.component.ts

import {Component, OnInit} from '@angular/core'; // Importing OnInit hook

import {HttpClient, HttpHeaders} from '@angular/common/http';

@Component({

selector: 'app-root',

templateUrl: './app.component.html',

styleUrls: ['./app.component.css']

})

export class AppComponent implements OnInit {

// Implementing OnInit

constructor(private http: HttpClient) {}

title = 'api-angular';

ngOnInit() {

// API Call

let headers = new HttpHeaders({

'x-rapidapi-host': 'random-facts2.p.rapidapi.com',

'x-rapidapi-key': 'your-api-key'

});

this.http

.get<any>('https://random-facts2.p.rapidapi.com/getfact', {

headers: headers

})

.subscribe(data => {

console.log(data);

});

}

}

Now our application is ready to make API calls. Reload your application and check your console. You will see a random fact like this:

Wrap Up

This guide was an introduction to consuming APIs in Angular. We hope that now you can start using APIs in your awesome Angular projects.

How to Call APIs in Angular? (2024)
Top Articles
Osmotic pressure | Description, Types, Measurement, & Applications
The Official Portal of the UAE Government
Golden Abyss - Chapter 5 - Lunar_Angel
Cappacuolo Pronunciation
Arkansas Gazette Sudoku
Craglist Oc
30% OFF Jellycat Promo Code - September 2024 (*NEW*)
Gameday Red Sox
Roblox Character Added
Erskine Plus Portal
Rls Elizabeth Nj
Strange World Showtimes Near Cmx Downtown At The Gardens 16
A Fashion Lover's Guide To Copenhagen
World Cup Soccer Wiki
Qhc Learning
What Time Chase Close Saturday
“In my day, you were butch or you were femme”
60 X 60 Christmas Tablecloths
Webcentral Cuny
Craigslist Missoula Atv
Pay Boot Barn Credit Card
Abby's Caribbean Cafe
Craigslist Sparta Nj
Sulfur - Element information, properties and uses
Craigslist Personals Jonesboro
Dulce
Air Quality Index Endicott Ny
Bòlèt Florida Midi 30
Jermiyah Pryear
Trivago Myrtle Beach Hotels
Netwerk van %naam%, analyse van %nb_relaties% relaties
Labcorp.leavepro.com
Garden Grove Classlink
Sony Wf-1000Xm4 Controls
Wells Fargo Bank Florida Locations
Martin Village Stm 16 & Imax
Sports Clips Flowood Ms
Matlab Kruskal Wallis
Justin Mckenzie Phillip Bryant
The Legacy 3: The Tree of Might – Walkthrough
Personalised Handmade 50th, 60th, 70th, 80th Birthday Card, Sister, Mum, Friend | eBay
ATM Near Me | Find The Nearest ATM Location | ATM Locator NL
Eastern New Mexico News Obituaries
2008 DODGE RAM diesel for sale - Gladstone, OR - craigslist
Culvers Lyons Flavor Of The Day
How to Print Tables in R with Examples Using table()
Cocorahs South Dakota
Mathews Vertix Mod Chart
Benjamin Franklin - Printer, Junto, Experiments on Electricity
Spongebob Meme Pic
Lux Nails & Spa
Ravenna Greataxe
Latest Posts
Article information

Author: Amb. Frankie Simonis

Last Updated:

Views: 5717

Rating: 4.6 / 5 (76 voted)

Reviews: 91% of readers found this page helpful

Author information

Name: Amb. Frankie Simonis

Birthday: 1998-02-19

Address: 64841 Delmar Isle, North Wiley, OR 74073

Phone: +17844167847676

Job: Forward IT Agent

Hobby: LARPing, Kitesurfing, Sewing, Digital arts, Sand art, Gardening, Dance

Introduction: My name is Amb. Frankie Simonis, I am a hilarious, enchanting, energetic, cooperative, innocent, cute, joyous person who loves writing and wants to share my knowledge and understanding with you.