HTTP Client and API Calls
Level: Intermediate
- HttpClient module and setup
- GET, POST, PUT, DELETE requests
- Request headers and options
- Error handling
- Response typing
- SMS API example
Why This Matters
Angular applications consume backend APIs. HttpClient = standard way to make HTTP requests. Understanding HTTP client essential for backend integration.
HttpClient Setup
// app.config.ts
import { provideHttpClient } from '@angular/common/http';
export const appConfig: ApplicationConfig = {
providers: [
provideHttpClient()
]
};
Or in module:
// app.module.ts
import { HttpClientModule } from '@angular/common/http';
@NgModule({
imports: [HttpClientModule],
declarations: [AppComponent],
bootstrap: [AppComponent]
})
export class AppModule { }
GET Request
// student.service.ts
import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
@Injectable({ providedIn: 'root' })
export class StudentService {
private apiUrl = 'https://api.school.in/api/students';
constructor(private http: HttpClient) {}
// Get all students
getStudents() {
return this.http.get<Student[]>(this.apiUrl);
}
// Get single student
getStudent(id: number) {
return this.http.get<Student>(`${this.apiUrl}/${id}`);
}
}
interface Student {
id: number;
name: string;
email: string;
className: string;
}
get<T>(url) = typed response. Returns Observable.
POST Request
createStudent(student: Omit<Student, 'id'>) {
return this.http.post<Student>(
this.apiUrl,
student,
{
headers: { 'Content-Type': 'application/json' }
}
);
}
post<T>(url, body, options) = create new resource.
PUT/PATCH/DELETE
// Update student
updateStudent(id: number, student: Student) {
return this.http.put<Student>(
`${this.apiUrl}/${id}`,
student
);
}
// Partial update
partialUpdate(id: number, changes: Partial<Student>) {
return this.http.patch<Student>(
`${this.apiUrl}/${id}`,
changes
);
}
// Delete student
deleteStudent(id: number) {
return this.http.delete(`${this.apiUrl}/${id}`);
}
Query Parameters
// Get students with filters
getStudentsByClass(className: string) {
return this.http.get<Student[]>(this.apiUrl, {
params: {
className: className,
skip: '0',
take: '10'
}
});
}
params = query string (?className=10&skip=0&take=10).
Headers
getWithAuth(token: string) {
return this.http.get<any>(this.apiUrl, {
headers: {
'Authorization': `Bearer ${token}`,
'X-Custom-Header': 'value'
}
});
}
Error Handling
import { catchError } from 'rxjs';
import { throwError } from 'rxjs';
getStudents() {
return this.http.get<Student[]>(this.apiUrl).pipe(
catchError(error => {
console.error('Error:', error);
return throwError(() => new Error('Failed to load students'));
})
);
}
// In component
loadStudents() {
this.studentService.getStudents().subscribe({
next: (data) => {
this.students = data;
},
error: (error) => {
this.errorMessage = error.message;
},
complete: () => {
this.loading = false;
}
});
}
.pipe() = transform Observable.
catchError() = handle errors.
Complete SMS Service
@Injectable({ providedIn: 'root' })
export class StudentService {
private apiUrl = 'https://api.sms.school/api/students';
constructor(private http: HttpClient) {}
getAll() {
return this.http.get<Student[]>(this.apiUrl);
}
getById(id: number) {
return this.http.get<Student>(`${this.apiUrl}/${id}`);
}
create(student: Omit<Student, 'id'>) {
return this.http.post<Student>(this.apiUrl, student);
}
update(id: number, student: Student) {
return this.http.put<Student>(`${this.apiUrl}/${id}`, student);
}
delete(id: number) {
return this.http.delete(`${this.apiUrl}/${id}`);
}
getByClass(className: string) {
return this.http.get<Student[]>(this.apiUrl, {
params: { className }
});
}
}
Key Takeaways
HttpClient= standard HTTP libraryget<T>()= GET request with typed responsepost<T>()= POST requestput<T>()= PUT requestdelete()= DELETE requestparams= query parametersheaders= custom headers.pipe()= transform ObservablecatchError()= handle errors- Returns Observable (need to subscribe)
HttpClient returns Observables, not Promises. Different from JavaScript fetch(). Observables are more powerful for cancellation, retries, transformations.
- Not importing HttpClientModule — HttpClient not available
- Forgetting to subscribe — Nothing happens
- Not typing response — Lose autocomplete/type safety
- Not handling errors — Errors not caught
- Not unsubscribing — Memory leaks
Use ChatGPT, Claude, or Copilot to go deeper on HttpClient. Try these prompts:
"Why Observable instead of Promise?""How do you send headers in HttpClient?""What's difference between pipe and subscribe?""Quiz me on HTTP requests"
💡 Tip: After reading this article, paste your own code into AI and ask "What could go wrong here and why?" — fastest way to find edge cases and deepen understanding.