Chapter 7.2โ˜• 15 min read

POST, PUT, DELETE with TypeScript Models

TypeScript models ensure you send and receive the right data. POST creates, PUT replaces, DELETE removes โ€” all with type safety.

01Why TypeScript Models Matter

TypeScript models define exactly what data you send to and receive from the API. They catch errors at compile time, not runtime.

// Model for creating a new biryani
export interface CreateBiryani {
  name: string;
  price: number;
  category: string;
  description: string;
}

// Model for updating โ€” partial fields allowed
export interface UpdateBiryani extends Partial<CreateBiryani> {
  id: number;
}

// Model for reading from API (includes server-generated id)
export interface Biryani extends CreateBiryani {
  id: number;
  rating: number;
  available: boolean;
  createdAt: string;
}

"Model = form โ€” bina model ke koi bhi data bhej sakte ho โ€” galat data jaayega."

Why separate Create and Update interfaces?

  • Create requires all fields โ€” you need name, price, category to create a biryani
  • Update is partial โ€” you might only update the price, not the name
  • Read includes server-generated fields โ€” id, rating, createdAt come from backend
  • TypeScript ensures at compile time that you don't send wrong data
02POST โ€” Create New Data

POST creates new data on the server. The server generates an id and returns the created object.

import { Component, inject } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Biryani, CreateBiryani } from './biryani.models';

@Component({...})
export class BiryaniFormComponent {
  private http = inject(HttpClient);

  createBiryani(name: string, price: number) {
    const newBiryani: CreateBiryani = {
      name,
      price,
      category: 'chicken',
      description: `Delicious ${name} biryani`
    };

    this.http.post<Biryani>('/api/biryani', newBiryani)
      .subscribe(created => {
        console.log('Created biryani with id:', created.id);
      });
  }
}

"POST = naya order dene ka button โ€” kitchen mein naya dish banega."

  • First argument: URL
  • Second argument: request body (the data to create)
  • Returns: the created object (with server-generated id)
  • Content-Type: application/json โ€” HttpClient sets this automatically
03PUT โ€” Update Existing Data

PUT replaces an entire resource with new data. You must send ALL fields, even unchanged ones.

updateBiryani(id: number, updates: UpdateBiryani) {
  // Send ALL fields โ€” PUT replaces the entire resource
  const fullUpdate: Biryani = {
    id,
    name: updates.name ?? existingName,
    price: updates.price ?? existingPrice,
    category: updates.category ?? existingCategory,
    description: updates.description ?? existingDesc,
    rating: existingRating,
    available: existingAvailable,
    createdAt: existingCreatedAt
  };

  this.http.put<Biryani>(`/api/biryani/${id}`, fullUpdate)
    .subscribe(updated => {
      console.log('Updated:', updated);
    });
}

"PUT = pura plate replace โ€” naya rice, naya masala, sab naya."

PUT vs PATCH:

  • PUT โ€” replaces the ENTIRE resource. Send all fields.
  • PATCH โ€” partial update. Send only the fields you want to change.
  • Most REST APIs support both. PUT is idempotent (same call multiple times = same result).

For PATCH:

this.http.patch<Biryani>(`/api/biryani/${id}`, { price: 399 })
  .subscribe(updated => console.log('Price updated:', updated));
04DELETE โ€” Remove Data

DELETE removes data from the server.

deleteBiryani(id: number) {
  if (confirm('Delete this biryani? Are you sure?')) {
    this.http.delete(`/api/biryani/${id}`)
      .subscribe({
        next: () => {
          console.log('Deleted successfully');
          this.loadBiryanis(); // Refresh list
        },
        error: (err) => {
          console.error('Delete failed:', err);
        }
      });
  }
}

"DELETE = order cancel โ€” hata do, khatam."

  • No body needed (most APIs โ€” some may accept an optional body)
  • Returns: 204 No Content (empty response) or the deleted item
  • Always confirm before delete โ€” prevent accidental data loss
  • After successful delete, refresh the list to reflect changes

Type for delete:

delete(id: number): Observable<void>
// void because 204 returns no body
05Complete CRUD Service Pattern

Here's the complete CRUD service pattern โ€” the standard recipe for every API service:

import { Injectable, inject } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
import { Biryani, CreateBiryani, UpdateBiryani } from './biryani.models';

@Injectable({ providedIn: 'root' })
export class BiryaniService {
  private http = inject(HttpClient);
  private apiUrl = '/api/biryani';

  // READ โ€” Get all
  getAll(): Observable<Biryani[]> {
    return this.http.get<Biryani[]>(this.apiUrl);
  }

  // READ โ€” Get by ID
  getById(id: number): Observable<Biryani> {
    return this.http.get<Biryani>(`${this.apiUrl}/${id}`);
  }

  // CREATE โ€” Post new
  create(data: CreateBiryani): Observable<Biryani> {
    return this.http.post<Biryani>(this.apiUrl, data);
  }

  // UPDATE โ€” Put full update
  update(id: number, data: UpdateBiryani): Observable<Biryani> {
    return this.http.put<Biryani>(`${this.apiUrl}/${id}`, data);
  }

  // DELETE โ€” Remove
  delete(id: number): Observable<void> {
    return this.http.delete<void>(`${this.apiUrl}/${id}`);
  }
}

"Ye 5 methods = standard CRUD recipe โ€” har service mein same pattern."

Every Angular HTTP service follows this pattern. Once you learn it, you can apply it to any resource โ€” users, products, orders, anything.

Key Takeaways

  • โœ… TypeScript models (Create, Update, Read interfaces) catch errors at compile time
  • โœ… POST creates new data โ€” returns created object with server-generated id
  • โœ… PUT replaces entire resource โ€” send ALL fields; PATCH for partial updates
  • โœ… DELETE removes data โ€” always confirm before deleting, handle 204 responses
  • โœ… Standard CRUD pattern: getAll, getById, create, update, delete โ€” reusable across all services
Course Search
Search across all chapters & stages
๐Ÿ“–

Search the course

Type any topic โ€” branching, stash, rebase, hooks โ€” and jump straight to that chapter.

merge branchesgit stashundo commitrebase