Activity 28: Research Rest API

A REST API is a set of web-based guidelines and principles for creating scalable and efficient web services. It follows the REST architectural style and is widely used for building and integrating software applications.

Key Principles of REST APIs

  1. Stateless

    • Every request from a client to a server must contain all the information needed to process the request.

    • The server doesn’t store client context between requests.

  2. Client-Server Architecture:

    • The client (frontend) and server (backend) are separate entities that interact via requests and responses.

    • This separation improves scalability and portability.

  3. Uniform Interface:

    • REST APIs should use consistent resource representations, typically URLs.

    • Example: GET /users for retrieving user data.

  4. Cacheable:

    • Responses must explicitly define whether they are cacheable or not to optimize performance.
  5. Layered System:

    • APIs should support intermediate layers, such as load balancers, proxies, or security layers, without affecting client interactions.
  6. Code on Demand (Optional):

    • The server can deliver executable code (like JavaScript) to the client for execution.

How REST APIs Work

  1. Request-Response Mechanism:

    • The client sends an HTTP request (e.g., GET, POST, PUT, DELETE).

    • The server processes the request and returns a response in a specific format, often JSON or XML.

  2. HTTP Methods:

    • GET: Retrieve a resource.

    • POST: Create a new resource.

    • PUT: Update an existing resource.

    • DELETE: Remove a resource.

    • PATCH: Partially update a resource.

  3. Endpoints and Resources:

  4. HTTP Status Codes:

    • Standardized codes indicate the result of a request:

      • 200 OK: Success.

      • 201 Created: Resource successfully created.

      • 404 Not Found: Resource not found.

      • 500 Internal Server Error: Server-side error.

Common Use Cases of REST APIs

  1. Web Applications:

    • Backend services for managing data (e.g., e-commerce platforms).

    • Example: Fetching product data in an online store.

  2. Mobile Applications:

    • Syncing data between the app and server.

    • Example: Social media apps using REST APIs to fetch posts or messages.

  3. Third-Party Integrations:

    • Connecting with external services (e.g., payment gateways, Google Maps).
  4. IoT Devices:

    • Communication between devices and servers.
  5. Cloud Applications:

    • Enabling interaction with cloud services (e.g., AWS, Azure).

REST API in Angular Applications

Step 1: Import HttpClientModule In app.module.ts:

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

        @NgModule({
          declarations: [AppComponent],
          imports: [BrowserModule, HttpClientModule],
          bootstrap: [AppComponent]
        })
        export class AppModule {}

Step 2: Create a Service In user.service.ts:

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';

@Injectable({
  providedIn: 'root',
})
export class UserService {
  private apiUrl = 'https://api.example.com/users';

  constructor(private http: HttpClient) {}

  getUsers(): Observable<any> {
    return this.http.get(this.apiUrl);
  }

  addUser(user: any): Observable<any> {
    return this.http.post(this.apiUrl, user);
  }
}

Step 3: Use the Service in a Component In user.component.ts:

import { Component, OnInit } from '@angular/core';
import { UserService } from './user.service';

@Component({
  selector: 'app-user',
  template: `
    <div *ngFor="let user of users">
      {{ user.name }}
    </div>
  `,
})
export class UserComponent implements OnInit {
  users: any[] = [];

  constructor(private userService: UserService) {}

  ngOnInit() {
    this.userService.getUsers().subscribe((data) => (this.users = data));
  }
}

Best Practices for Implementing REST APIs in Angular

  1. Use HttpClient:

    • Leverage Angular's HttpClient for HTTP requests.

    • It provides built-in support for observables and streamlined error handling.

  2. Error Handling:

    • Use catchError from RxJS to handle API errors gracefully.
import { catchError } from 'rxjs/operators';
import { throwError } from 'rxjs';

this.http.get(this.apiUrl).pipe(
  catchError((error) => {
    console.error('Error occurred:', error);
    return throwError(error);
  })
);
  1. Environment-Specific Configuration:

    • Store API URLs in environment-specific files (e.g., environment.ts).
export const environment = {
  production: false,
  apiUrl: 'https://api.example.com',
};
  1. Avoid Hardcoding URLs:

    • Use a single place for base URLs to enable easier updates.
  2. Implement Caching:

    • Cache API responses to reduce unnecessary network calls.
  3. Loading Indicators:

    • Show a loader while waiting for API responses to enhance user experience.
  4. Secure API Calls:

    • Use HTTPS for communication.

    • Secure API tokens in headers.

const headers = { Authorization: 'Bearer token' };
this.http.get(this.apiUrl, { headers }).subscribe();
  1. Pagination and Filtering:

    • Implement and handle pagination, sorting, and filtering for large datasets.
  2. Follow RESTful Conventions:

    • Use appropriate HTTP methods and status codes.

    • Structure endpoints logically.

  3. Testing:

    • Test REST API calls with tools like Postman or automated tests in Angular.

By following these principles and practices, you can create reliable, maintainable, and scalable applications that effectively use REST APIs in Angular.