Skip to content
beginner Phase 9 · HTTP Client and Interceptors

POST, PUT, and DELETE Requests

Send bodies, headers, and query parameters to your API.

35m
0 problems
Topic Progress 0%

CRUD Operations

HttpClient provides methods for all HTTP verbs needed in CRUD operations.

POST — Create

createUser(user: CreateUserRequest): Observable<User> {
  return this.http.post<User>('/api/users', user);
}

// Usage
this.userService.createUser({ name: 'Alice', email: 'alice@example.com' })
  .subscribe(createdUser => {
    console.log('Created:', createdUser);
  });

PUT — Full Update

updateUser(id: number, user: User): Observable<User> {
  return this.http.put<User>(`/api/users/${id}`, user);
}

PATCH — Partial Update

updateUserEmail(id: number, email: string): Observable<User> {
  return this.http.patch<User>(`/api/users/${id}`, { email });
}

DELETE — Remove

deleteUser(id: number): Observable<void> {
  return this.http.delete<void>(`/api/users/${id}`);
}

Complete CRUD Service

@Injectable({ providedIn: 'root' })
export class UserService {
  private http = inject(HttpClient);
  private baseUrl = '/api/users';

  getUsers(): Observable<User[]> {
    return this.http.get<User[]>(this.baseUrl);
  }

  getUser(id: number): Observable<User> {
    return this.http.get<User>(`${this.baseUrl}/${id}`);
  }

  createUser(user: CreateUserRequest): Observable<User> {
    return this.http.post<User>(this.baseUrl, user);
  }

  updateUser(id: number, user: Partial<User>): Observable<User> {
    return this.http.patch<User>(`${this.baseUrl}/${id}`, user);
  }

  deleteUser(id: number): Observable<void> {
    return this.http.delete<void>(`${this.baseUrl}/${id}`);
  }
}

Headers and Query Parameters

HttpClient allows per-request headers and query parameters.

Setting Headers

getUsers(): Observable<User[]> {
  return this.http.get<User[]>('/api/users', {
    headers: new HttpHeaders({
      'Authorization': 'Bearer token123',
      'Accept': 'application/json',
    }),
  });
}

Using HttpParams

searchUsers(query: string, page: number): Observable<User[]> {
  const params = new HttpParams()
    .set('q', query)
    .set('page', page.toString())
    .set('limit', '20');

  return this.http.get<User[]>('/api/users/search', { params });
}

HttpParams Methods

const params = new HttpParams()
  .set('key', 'value')      // Set or replace
  .append('key', 'value2')  // Add another value
  .delete('key');           // Remove

params.get('key');    // string | null
params.getAll('key'); // string[]
params.has('key');    // boolean
params.toString();    // 'key=value'

Per-Request Options

this.http.get<User[]>('/api/users', {
  headers: { 'Authorization': 'Bearer token' },
  params: { page: '1', limit: '20' },
  responseType: 'json',  // 'json' | 'text' | 'blob' | 'arraybuffer'
  withCredentials: false, // Include cookies
});

Quiz

1. Which HttpClient method sends a POST request?

Question 1 options

2. How do you safely build query parameters?

Question 2 options

3. What is the difference between PUT and PATCH?

Question 3 options

Flashcards

Question

How do you send a POST request?

Answer

http.post<T>(url, body) — second argument is the request body.

Question

How do you build query parameters safely?

Answer

HttpParams with .set() and .append() — safely encodes values.

Question

PUT vs PATCH?

Answer

PUT replaces entire resource. PATCH updates only specified fields.

Revision Notes

Key Takeaways

  • 1. http.post() sends bodies, http.delete() removes resources
  • 2. HttpParams safely encodes query strings
  • 3. Headers can be set per request
  • 4. PUT replaces; PATCH updates partially

Interview Tips

  • • Explain the difference between PUT and PATCH
  • • Be ready to describe HttpParams usage
  • • Mention per-request headers and options

Cheat Sheet

HTTP Methods Cheat Sheet

CRUD:

http.get<T>(url)
http.post<T>(url, body)
http.put<T>(url, body)
http.patch<T>(url, partialBody)
http.delete<T>(url)

Headers:

headers: { 'Authorization': 'Bearer token' }

Query params:

const params = new HttpParams().set('key', 'value')
http.get(url, { params })

Continue Learning