Activity 28: Research Rest API

Activity 28: Research Rest API

REST API (Representational State Transfer Application Programming Interface)

REST API is a design architectural style that leverages HTTP protocols for communication between client and server. RESTful APIs are widely used for building scalable and stateless web services and are integral in web and mobile application development.

Key Principles of REST

  • Statelessness
    Each client request must contain all the necessary information for the server to fulfill it. No client context is stored on the server between requests.

  • Client-Server Architecture

    • Client: Responsible for the user interface and user experience.

    • Server: Responsible for handling requests and data storage. This separation enhances scalability and modularity.

  • Uniform Interface
    REST APIs should have a consistent and predictable design for easier implementation and use. This is achieved via:

    • Resource identification (e.g., /users or /products).

    • Resource representation (usually in JSON or XML format).

  • Cacheability
    Responses from the server must indicate whether they are cacheable, improving performance and reducing load.

  • Layered System
    The API architecture can have layers for security, load balancing, and other concerns, but these layers should be invisible to the client.

  • Code on Demand (Optional)
    The server can extend the client’s functionality by sending executable code (e.g., JavaScript), though this is not commonly used.

How REST API Works

  • Endpoints: URLs represent specific resources (e.g., /api/users/123).

  • HTTP Methods: Define actions on resources:

    • GET: Retrieve data.

    • POST: Create new resources.

    • PUT/PATCH: Update existing resources.

    • DELETE: Remove resources.

  • Request and Response: Communication is done via HTTP with JSON as the common data format.

Common Use Cases of REST APIs

  1. Web Applications

    • Providing backend services for web apps.

    • Example: A weather API fetching live weather updates.

  2. Mobile Applications

    • Enabling mobile apps to interact with cloud-based services.

    • Example: A food delivery app fetching restaurant menus.

  3. Third-Party Integration

    • Connecting applications with external services.

    • Example: Payment gateways like Stripe or PayPal.

  4. IoT Devices

    • Allowing communication between IoT devices and cloud servers.

    • Example: A smart thermostat API controlling temperature settings.

Best Practices for Implementing REST APIs

  1. Versioning
    Use versioning in URLs (e.g., /api/v1/) to ensure backward compatibility.

  2. Use Proper HTTP Methods
    Align your API methods with REST principles.

  3. Secure APIs

    • Use HTTPS to encrypt data in transit.

    • Implement authentication and authorization (e.g., OAuth 2.0, JWT).

  4. Standardized Error Handling
    Return meaningful error messages with appropriate HTTP status codes (e.g., 404 Not Found).

  5. Pagination
    For large datasets, implement pagination, filtering, and sorting.

  6. Documentation
    Provide clear API documentation using tools like Swagger or Postman.

Implementing REST APIs in Angular

Angular provides a robust framework to consume and implement REST APIs efficiently. Here's how to do it:

  1. HTTPClient Module
    Use Angular's HttpClient module to communicate with APIs.

    Example:

     import axios from 'axios';
    
     // GET users
     axios.get('/api/users')
       .then(response => console.log(response.data))
       .catch(error => console.error(error));
    
     // POST new user
     axios.post('/api/users', { name: 'John', age: 30 })
       .then(response => console.log(response.data))
       .catch(error => console.error(error));
    
  2. Reactive Forms for Data Submission
    Use Angular's forms module to handle user inputs and post data to APIs.

  3. Error Handling
    Use catchError from RxJS to handle API errors gracefully.

     import { catchError } from 'rxjs/operators';
     this.http.get('/api/users')
       .pipe(catchError(error => of([])))
       .subscribe(data => console.log(data));
    
  4. Best Practices in Angular

    • Services: Use services to abstract API calls.

    • Interceptors: Add interceptors for logging, error handling, or adding authorization headers.

    • Environment Files: Store API base URLs in environment.ts files.

  5. Use Async/Await for Cleaner Code
    Example:

     async fetchData() {
       this.users = await this.http.get('/api/users').toPromise();
     }