HomeBlogWeb DevelopmentHow to Make API Calls in Angular Application? [Step-by-Step]

How to Make API Calls in Angular Application? [Step-by-Step]

Published
18th Jun, 2024
Views
view count loader
Read it in
8 Mins
In this article
    How to Make API Calls in Angular Application? [Step-by-Step]

    Front-end applications in today’s programming world use HTTP protocol modules to talk to the back-end services. Almost all current browsers make this communication via two ways, one by HTTPrequests through XMLHttpRequest interface and the other by the API fetch() method call.

    We usually make API calls to remote HTTP servers via HttpClient module of Angular 10 by sending HTTP requests. HttpClient has methods which perform HTTP requests. HttpClient is an injectable class for Angular 10. The methods of this class have request methods with many types of signatures, and their return types are different based on the signature of the request, thus giving different response types. We will study how to make API calls in angular in detail in the subsequent passage.

    In this extensive guide, I will delve into the importance of API calls in Angular, the meticulous setup of the development environment, and provide a detailed walkthrough of making API calls, complete with code snippets and visual aids. I recommend  you can learn more on Angular training course. 

    How to Set Up the Angular Environment for API Calls? 

    In the realm of understanding how to make API calls in angular , Let us first setup the Angular environment.  

    Before embarking on the journey of making API calls, it is imperative to ensure that the Angular environment is set up optimally. In this section I will guide you through the configuration of Angular services, modules, and dependencies, laying the groundwork for effective communication with APIs. 

    To set up the Angular environment for API calls, Do follow these steps: 

    1. Install Angular CLI: 

    Install the Angular Command Line Interface (CLI) globally using npm: 

    npm install -g @angular/cli 

    2. Create a New Angular Project: 

    Create a new Angular project using the CLI by running the following commands: 

    ng new your-project-name 
    cd your-project-name 


    3. Generate a Service: 

    Generate a service to encapsulate API call logic: 

    ng generate service your-service-name 

    Now we have carried out the basic angular setup. In the next sections, we will write the logic to perform API calls in Angular.

    How to Make API Calls in Angular App? [Step-by-Step]

    The correct approach towards how to call API in Angular app includes the following:

    A. Create Constants

    We need to set global variables in Angular 10 to access our variables synchronously throughout our application. 

    We declare Global variables in a Global Constant file. Create a folder under src/app and name it config. To create the global constant file, name it constants.ts and place it under src/app/config folder.

    Eg: create the following file: 

    src/app/config/constants.ts 

    Open this file and put global constants like API_ENDPOINT, API_MOCK_ENDPOINT etc. These global variables will be used later in Component files like AppComponent so that they can be used like Site constants.

     B. Declaring Global Constants

    // Angular Modules
    import { Injectable } from '@angular/core'; 
    @Injectable() 
    export class Constants {
    public readonly API_ENDPOINT: string = ' https://www.userdomain.com/'; 
    public readonly API_MOCK_ENDPOINT: string = 'https://www.userdomainmock.com/'; 
    public static TitleOfSite: string = " Making API calls the Right Way by Monica"; 
    
    An example of AppComponent using the above global constant is: 
    Edit the app.component.ts file from the src/app folder: 
    src/app/app.component.ts: 
    import { Component, OnInit } from '@angular/core';
    import{ Constants } from './config/constants'; 
    @Component({ 
      selector: 'app-root', 
      templateUrl: './app.component.html', 
      styleUrls: ['./app.component.css'] 
    }) 
    export class AppComponent implements OnInit{ 
        title = Constants.TitleOfSite; 
        constructor() { 
            console.log(GlobalConstants.API_ENDPOINT); 
        } 
        ngOnInit() { 
            console.log(this.title); 
        } 
    

    C. Run the project by navigating to the project folder and calling ng serve : 

    $ cd hello-world  
    $ ng serve  

    The output will be seen in the browser: https://www.userdomain.com/ 

    Making API Calls the Right Way by Monica.

    D. Create a Service

    To create a service in Angular 10, create a file api-http.service.ts in the src/app/core/services folder.

    Add the following code in the file as below: 

    // Angular Modules 
    import { Injectable } from '@angular/core'; 
    import { HttpClient } from '@angular/common/http'; 
    @Injectable() 
    export class ApiHttpService { 
    constructor( 
    // Angular Modules 
    private http: HttpClient 
    ) { } 
    public get(url: string, options?: any) { 
    return this.http.get(url, options); 
    } 
    public post(url: string, data: any, options?: any) { 
    return this.http.post(url, data, options); 
    } 
    public put(url: string, data: any, options?: any) { 
    return this.http.put(url, data, options); 
    } 
    public delete(url: string, options?: any) { 
    return this.http.delete(url, options); 
    } 
    }

    Use HTTPClient Library

    HttpClient Library is present in @angular/common/http folder. The older version of HttpClient was in @angular/http folder, this is replaced by the upgraded version of the same in @angular/common/http folder.

    Almost all current browsers communicate with APIs via two ways, one by HTTPrequests through XMLHttpRequest interface and the other by the API fetch() method call.

    The HttpClient module is built over XMLHttpRequest interface. It wraps all the complexities of this interface and provides extra features like: RxJS Obervables, Interceptors for requests and responses, Typed requests and responses, Error handling techniques, ease in Testing Modules, etc. 

    Benefits of Using HTTPClient Library

    HttpClient is a module found in angular/common/http module. HttpClient is based on XMLHttpRequest interface, the Interface which is commonly given by most modern browsers. HttpClient gives us a lot more than XMLHttpRequest, and some of its benefits are:

    1. It gives us ease in using testing modules.
    2. It has request and response objects in strongly typed manner.
    3. It has APIs Support with Observable class object.
    4. It provides error handling modules.

    Importing the library

    In order to use HttpClient library we need to import HttpClientModule from the @angular/common/http package and include the library in the imports array of the App module : 

    Edit the AppModule file in the src/app folder and add the line on top of the file as follows: 

    src/app/app.module.ts: 
    import { HttpClientModule } from '@angular/common/http'; 

    Configure HTTPClient

    Including HttpClient: 

    Once done, include HttpClientModule in the imports array of the app.module and further use it:

    import { NgModule }         from '@angular/core';
    import { BrowserModule }    from '@angular/platform-browser';
    import { HttpClientModule } from '@angular/common/http';
    @NgModule({
      imports: [
        BrowserModule,
        // import HttpClientModule after BrowserModule.
        HttpClientModule,
      ],
      declarations: [
        AppComponent,
      ],
      bootstrap: [ AppComponent ]
    })
    export class AppModule {}
    …

    Now we are ready to use the HttpClient library to send HTTP requests or receive API response. 

    A. Injecting HttpClient into our Application: 

    Once we have  imported HttpClientModule into the AppModule, we can inject the HttpClient into our application as:

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

    B. Create a query parameter

    Getting JSON data

    In this example we will request JSON data from the API server. Here our app needs a configuration file on the server, config.json, that specifies resource URLs.

    {
      "demoUrl": "api/demo",
      "filename": "assets/demotextfile.txt"
    }
    The ConfigService fetches this file with a get() method from HttpClient library as follows:
    
    configUrl = 'assets/config.json';
    getConfig() {
      return this.http.get(this.configUrl);
    }

    A component, such as ConfigComponent, injects the ConfigService and this getConfig service method is called from the component as for example:

    showConfig() {
      this.configService.getConfig()
        .subscribe((data: Config) => this.config = {
            demoUrl: data['demoUrl'],
            filename:  data['filename']
        });
    }

    The service method returns an Observable object of configuration data. Thus the component subscribes to the method's return value. The subscription callback copies the data fields into the component's config object, which binds the data in the component template for display.

    We can get the Observable object of typed HTtpResponse from the HttpClient as follows:

    getConfigResponse(): Observable<HttpResponse<Config>> {
      return this.http.get<Config>(
        this.configUrl, { observe: 'response' });
    }

    Here, HttpClient.get() returns an Observable object of typed HttpResponse rather than just the JSON data.

    The showConfigResponse() method of the component displays the response headers as well as the configuration.

    C. Create Error Handler

    HttpClient returns an error object instead of a successful response if a request fails on the server. This usually happens due to a request fail, poor network connection or other network related issues.

    We can create an error handler component by adding a second callback to the.subscribe():

    showConfig() {
      this.configService.getConfig()
        .subscribe(
          (data: Config) => this.config = { ...data }, // success path
          error => this.error = error // error path
        );
    }

    We can give different reasons and feedback for a failed request, but displaying the error object can also help at times. 

    @angular/common/http

    @angular/common/http implements an HTTP client API for Angular apps that relies on the XMLHttpRequest interface exposed by browsers.

    This includes testability features, typed request and response objects, request and response interception, observable APIs, and streamlined error handling.

    Entry point exports

    NgModules
    HttpClientJsonpModuleConfigures the dependency injector for HttpClient with supporting services for JSONP. Without this module, Jsonp requests reach the backend with method JSONP, where they are rejected.
    HttpClientModuleConfigures the dependency injector for HttpClient with supporting services for XSRF. Automatically imported by HttpClientModule.
    HttpClientXsrfModuleConfigures XSRF protection support for outgoing requests.
    Classes
    HttpBackendA final HttpHandler which will dispatch the request via browser HTTP APIs to a backend.
    HttpClientPerforms HTTP requests. This service is available as an injectable class, with methods to perform HTTP requests. Each request method has multiple signatures, and the return type varies based on the signature that is called (mainly the values of observe and responseType).
    HttpErrorResponseA response that represents an error or failure, either from a non-successful HTTP status, an error while executing the request, or some other failure which occurred during the parsing of the response.
    HttpHandlerTransforms an HttpRequest into a stream of HttpEvents, one of which will likely be a HttpResponse.
    HttpHeaderResponseA partial HTTP response which only includes the status and header data, but no response body.
    HttpHeadersRepresents the header configuration options for an HTTP request. Instances are immutable. Modifying methods return a cloned instance with the change. The original object is never changed.
    HttpParamsAn HTTP request/response body that represents serialized parameters, per the MIME type application/x-www-form-urlencoded.
    HttpRequestAn outgoing HTTP request with an optional typed body.
    HttpResponseA full HTTP response, including a typed response body (which may be null if one was not returned).
    HttpResponseBaseBase class for both HttpResponse and HttpHeaderResponse.
    HttpUrlEncodingCodecProvides encoding and decoding of URL parameter and query-string values.
    HttpXhrBackendUses XMLHttpRequest to send requests to a backend server.
    HttpXsrfTokenExtractorRetrieves the current XSRF token to use with the next outgoing request.
    JsonpClientBackendProcesses an HttpRequest with the JSONP method, by performing JSONP style requests.
    JsonpInterceptorIdentifies requests with the method JSONP and shifts them to the JsonpClientBackend.
    XhrFactoryA wrapper around the XMLHttpRequest constructor.
    Structures
    HttpDownloadProgressEventA download progress event.
    HttpEventTypeType enumeration for the different kinds of HttpEvent.
    HttpInterceptorIntercepts and handles an HttpRequest or HttpResponse.
    HttpParameterCodecA codec for encoding and decoding parameters in URLs.
    HttpProgressEventBase interface for progress events.
    HttpSentEventAn event indicating that the request was sent to the server. Useful when a request may be retried multiple times, to distinguish between retries on the final event stream.
    HttpUploadProgressEventAn upload progress event.
    HttpUserEventA user-defined event.
    Types
    HTTP_INTERCEPTORSA multi-provider token that represents the array of registered HttpInterceptor objects.
    HttpEventUnion type for all possible events on the response stream.

    HttpClient vs HttpBackend

    A. HttpBackend

    • A final HttpHandler which will dispatch the request via browser HTTP APIs to a backend.
    • Interceptors sit between the HttpClient interface and the HttpBackend.
    • When injected, HttpBackend dispatches requests directly to the backend, without going through the interceptor chain.
    abstract class HttpBackend implements HttpHandler {
      abstract handle(req: HttpRequest<any>): Observable<HttpEvent<any>>
    }

    B. HttpClient

    • Performs HTTP requests. This service is available as an injectable class, with methods to perform HTTP requests. Each request method has multiple signatures, and the return type varies based on the signature that is called (mainly the values of observe and responseType).
    • Note that the response Type options value is a String that identifies the single data type of the response. A single overload version of the method handles each response type. The value of responseType cannot be a union, as the combined signature could imply.
    class HttpClient {
    request(first: string | HttpRequest<any>, url?: string, options: { body?: any; headers?: HttpHeaders | { [header: string]: string | string[]; }; observe?: HttpObserve; params?: HttpParams | { [param: string]: string | string[]; }; reportProgress?: boolean; responseType?: "arraybuffer" | ... 2 more ... | "json"; withCredentials?: boolean; } = {}): Observable<any>
      delete(url: string, options: { headers?: HttpHeaders | { [header: string]: string | string[]; }; observe?: HttpObserve; params?: HttpParams | { [param: string]: string | string[]; }; reportProgress?: boolean; responseType?: "arraybuffer" | ... 2 more ... | "json"; withCredentials?: boolean; } = {}): Observable<any>
      get(url: string, options: { headers?: HttpHeaders | { [header: string]: string | string[]; }; observe?: HttpObserve; params?: HttpParams | { [param: string]: string | string[]; }; reportProgress?: boolean; responseType?: "arraybuffer" | ... 2 more ... | "json"; withCredentials?: boolean; } = {}): Observable<any>
      head(url: string, options: { headers?: HttpHeaders | { [header: string]: string | string[]; }; observe?: HttpObserve; params?: HttpParams | { [param: string]: string | string[]; }; reportProgress?: boolean; responseType?: "arraybuffer" | ... 2 more ... | "json"; withCredentials?: boolean; } = {}): Observable<any>
      jsonp<T>(url: string, callbackParam: string): Observable<T>
      options(url: string, options: { headers?: HttpHeaders | { [header: string]: string | string[]; }; observe?: HttpObserve; params?: HttpParams | { [param: string]: string | string[]; }; reportProgress?: boolean; responseType?: "arraybuffer" | ... 2 more ... | "json"; withCredentials?: boolean; } = {}): Observable<any>
      patch(url: string, body: any, options: { headers?: HttpHeaders | { [header: string]: string | string[]; }; observe?: HttpObserve; params?: HttpParams | { [param: string]: string | string[]; }; reportProgress?: boolean; responseType?: "arraybuffer" | ... 2 more ... | "json"; withCredentials?: boolean; } = {}): Observable<any>
      post(url: string, body: any, options: { headers?: HttpHeaders | { [header: string]: string | string[]; }; observe?: HttpObserve; params?: HttpParams | { [param: string]: string | string[]; }; reportProgress?: boolean; responseType?: "arraybuffer" | ... 2 more ... | "json"; withCredentials?: boolean; } = {}): Observable<any>
      put(url: string, body: any, options: { headers?: HttpHeaders | { [header: string]: string | string[]; }; observe?: HttpObserve; params?: HttpParams | { [param: string]: string | string[]; }; reportProgress?: boolean; responseType?: "arraybuffer" | ... 2 more ... | "json"; withCredentials?: boolean; } = {}): Observable<any>
    }

    The request that we send by HttpClient always go through interceptor of Angular application and the request we send by HttpBackend will dispatch requests directly to the backend, without going through the interceptor chain. So we should use both HttpClient and HttpBackend to send a request.

    A Common Mistake of API Calls in Angular 

    While mastering how to make API calls in Angular is pivotal for robust applications, developers often encounter common pitfalls that can impact the performance and reliability of their code. One prevalent mistake to be wary of involves inadequate error handling during API calls. 

    Insufficient Error Handling

    A frequent oversight in Angular API development is neglecting to implement comprehensive error-handling mechanisms. When interacting with external APIs, unforeseen issues such as network errors, server downtimes, or invalid responses can occur. Failing to address these scenarios properly can result in unpredictable behavior and compromise the user experience. 

    To mitigate this common pitfall, developers must incorporate robust error-handling strategies in their Angular applications. Angular's HttpClient module, which facilitates HTTP requests, provides the catchError operator from the RxJS library. This operator enables developers to intercept errors and implement customized responses. 

    // api.service.ts 
    import { Injectable } from '@angular/core'; 
    import { HttpClient } from '@angular/common/http'; 
    import { Observable, throwError } from 'rxjs'; 
    import { catchError } from 'rxjs/operators'; 
     
    @Injectable({ 
      providedIn: 'root', 
    }) 
    export class ApiService { 
      private apiUrl = 'https://api.example.com'; 
     
      constructor(private http: HttpClient) {} 
     
      getData(): Observable<any> { 
        return this.http.get(`${this.apiUrl}/data`).pipe( 
          catchError((error) => { 
            console.error('Error fetching data:', error); 
            return throwError(error); 
          }) 
        ); 
      } 
     
     
      postData(data: any): Observable<any> { 
        return this.http.post(`${this.apiUrl}/post`, data).pipe( 
          catchError((error) => { 
            console.error('Error posting data:', error); 
            return throwError(error); 
          }) 
        ); 
      } 
    } 

    By incorporating catchError, developers can log errors for debugging purposes, gracefully handle unexpected situations, and prevent the application from crashing. Proper error handling not only contributes to a more stable application but also allows developers to provide meaningful feedback to users when issues arise, enhancing the overall user experience. Addressing this common mistake ensures that Angular applications remain resilient in the face of unpredictable conditions, fostering reliability and user trust. To delve deeper into the world of web development and enhance your skills, I recommend checking out earn more about web development, you can enroll in Web Development course. 

    Tips to Enhance API Calls in Angular Applications  

    As you embark on the journey of making API calls in Angular applications, certain strategic tips can significantly optimize your development process, ensuring a seamless user experience and robust application performance. 

    1. Implement Caching Strategies: One of the key optimizations you can introduce is the implementation of caching strategies for API responses. Caching allows you to store previously fetched data and reuse it, reducing the need for redundant requests to the server.  
    2. Effective Management of Loading States: Managing loading states is crucial for providing users with a clear understanding of ongoing API calls. Implement loading spinners, progress bars, or other visual cues to signify when an API call is in progress.  
    3. Optimize State Management: Efficient state management is fundamental to maintaining a coherent and stable application. As your Angular application interacts with APIs, careful consideration must be given to how the application state is managed. Utilize state management libraries like NgRx or Angular services to handle data flow seamlessly. 
    4. Handle Errors Gracefully: A robust error-handling mechanism is crucial for handling unexpected scenarios during API calls. Implement error handling in your Angular services to gracefully manage errors returned by the server. Utilize RxJS operators like catchError to intercept errors, log them for debugging purposes, and present meaningful error messages to users.  
    5. Optimize Network Requests: Consider optimizing network requests to minimize the impact on your application's performance. Techniques such as bundling multiple API requests into a single request (batching) or using pagination for large datasets can significantly reduce the number of network requests. 

    Adopting these best practices empowers you to build Angular applications that not only meet user expectations but also excel in terms of performance and reliability. You can learn more about API handling and best practices in the following Online Full Stack Developer Courses course.

    Why API Calls are Important in Angular Applications? 

    Angular applications thrive on the seamless integration of API calls, serving as the bridge for communication with external servers. This bidirectional flow of data is fundamental for real-time updates, dynamic content rendering, and maintaining synchronization between the client and server. Whether it's fetching information from a database or sending user inputs to a server, the significance of API calls in Angular cannot be overstated. 

    In the realm of Angular development, the integration of API calls plays a pivotal role in shaping the functionality and responsiveness of applications. Angular applications derive profound benefits from the seamless communication established with external servers through API calls. 

    1. Real-time Updates and Dynamic Content

    API calls serve as the conduit for real-time updates, enabling Angular applications to dynamically refresh content based on the latest data from servers. This capability is instrumental in scenarios where live information, such as stock prices, weather updates, or social media feeds, needs to be reflected instantaneously within the application. 

    2. Data Synchronization

    Angular applications often rely on data sourced from external databases or services. API calls facilitate the synchronization of this data between the client and server, ensuring that the application operates with the most current and accurate information. This synchronization is fundamental for maintaining data consistency and providing users with reliable and up-to-date content. 

    3. Enhanced User Experience

    The ability to fetch and send data through API calls contributes significantly to enhancing the user experience. Whether it's retrieving detailed user profiles, processing form submissions, or populating dynamic content, API calls empower Angular applications to deliver interactive and personalized experiences to users. 

    4. Seamless Integration with External Services

    Angular applications frequently need to integrate with external services, such as payment gateways, authentication providers, or third-party APIs. API calls enable seamless communication with these services, allowing developers to harness the full spectrum of functionalities offered by external resources while maintaining the integrity of their Angular applications. 

    Looking to boost your career? Join our Python course with certification! Learn the most in-demand programming language and secure your future. Don't miss out, enroll now!

    Conclusion

    The above article included all the information that on how to make API calls in Angular Applications. We worked with the Http module and HttpClient Module. We worked with services and efficient API Calls. We understood how to improve on calling API from an Angular Application. Enrolling in an KnowledgeHut's Angular online course would help you acquire Angular skills and stay competitive in the job market.

    Frequently Asked Questions (FAQs)

    1What is the role of HttpClient in Angular for API calls?

    HTTP Client in Angular facilitates seamless communication with APIs. It simplifies making HTTP requests, supporting various methods like GET and POST. Handling responses as Observables, ensures asynchronous operations, allowing developers to subscribe and process data or errors. With customizable options and support for interceptors, it offers flexibility in request configuration and global request/response modifications.  

    2What are the different HTTP methods supported in Angular for API calls?

    Angular supports various HTTP methods for API calls, including GET, POST, PUT, PATCH, and DELETE. These methods enable fetching data (GET), sending data to create or update resources (POST and PUT), updating partial resource data (PATCH), and removing resources (DELETE).  

    3How do I handle asynchronous operations in Angular when making API calls?

    In Angular, asynchronous operations when making API calls are handled using Observables. The subscribe method is employed to subscribe to the observable and execute code upon completion. This ensures that the application remains responsive while waiting for the API response. Developers can handle data or errors within the subscription, providing a clean and effective way to manage asynchronous behavior in Angular applications. 

    4What is the difference between Promises and Observables in Angular API calls?

    Promises and Observables are used for handling asynchronous operations in Angular API calls. Promises are single values that resolve or reject, while Observables can emit multiple values over time. Observables offer more features, like cancelation support and handling multiple events, making them suitable for complex asynchronous scenarios in Angular. 

    Profile

    Bala Krishna Ragala

    Blog Author

    Bala Krishna Ragala, Head of Engineering at upGrad, is a seasoned writer and captivating storyteller. With a background in EdTech, E-commerce, and LXP, he excels in building B2C and B2B products at scale. With over 15 years of experience in the industry, Bala has held key roles as CTO/Co-Founder at O2Labs and Head of Business (Web Technologies) at Zeolearn LLC. His passion for learning, sharing, and teaching is evident through his extensive training and mentoring endeavors, where he has delivered over 80 online and 50+ onsite trainings. Bala's strengths as a trainer lie in his extensive knowledge of software applications, excellent communication skills, and engaging presentation style.

    Share This Article
    Ready to Master the Skills that Drive Your Career?

    Avail your free 1:1 mentorship session.

    Select
    Your Message (Optional)

    Upcoming Web Development Batches & Dates

    NameDateFeeKnow more
    Course advisor icon
    Course Advisor
    Whatsapp/Chat icon