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
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.
Client-Server Architecture:
The client (frontend) and server (backend) are separate entities that interact via requests and responses.
This separation improves scalability and portability.
Uniform Interface:
REST APIs should use consistent resource representations, typically URLs.
Example:
GET /users
for retrieving user data.
Cacheable:
- Responses must explicitly define whether they are cacheable or not to optimize performance.
Layered System:
- APIs should support intermediate layers, such as load balancers, proxies, or security layers, without affecting client interactions.
Code on Demand (Optional):
- The server can deliver executable code (like JavaScript) to the client for execution.
How REST APIs Work
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.
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.
Endpoints and Resources:
Resources are identified via endpoints (URLs).
Example:
https://api.example.com/users/1
fetches details of user with ID1
.
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
Web Applications:
Backend services for managing data (e.g., e-commerce platforms).
Example: Fetching product data in an online store.
Mobile Applications:
Syncing data between the app and server.
Example: Social media apps using REST APIs to fetch posts or messages.
Third-Party Integrations:
- Connecting with external services (e.g., payment gateways, Google Maps).
IoT Devices:
- Communication between devices and servers.
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
Use HttpClient:
Leverage Angular's
HttpClient
for HTTP requests.It provides built-in support for observables and streamlined error handling.
Error Handling:
- Use
catchError
from RxJS to handle API errors gracefully.
- Use
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);
})
);
Environment-Specific Configuration:
- Store API URLs in environment-specific files (e.g.,
environment.ts
).
- Store API URLs in environment-specific files (e.g.,
export const environment = {
production: false,
apiUrl: 'https://api.example.com',
};
Avoid Hardcoding URLs:
- Use a single place for base URLs to enable easier updates.
Implement Caching:
- Cache API responses to reduce unnecessary network calls.
Loading Indicators:
- Show a loader while waiting for API responses to enhance user experience.
Secure API Calls:
Use HTTPS for communication.
Secure API tokens in headers.
const headers = { Authorization: 'Bearer token' };
this.http.get(this.apiUrl, { headers }).subscribe();
Pagination and Filtering:
- Implement and handle pagination, sorting, and filtering for large datasets.
Follow RESTful Conventions:
Use appropriate HTTP methods and status codes.
Structure endpoints logically.
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.