PUT Method

How to make PUT requests with speedcast-api

🔄 Using PUT Method

PUT requests replace an entire resource with a new representation. Always include all fields required for the resource, as missing fields may be removed.

Basic Usage

1. Import and Create API Client

import { SpeedcastApi } from 'speedcast-api';

// Create an API client
const api = new SpeedcastApi({
  baseURL: 'https://api.example.com'
});

2. Simple PUT Request

// Replace entire user resource
const completeUserData = {
  name: "John Doe",
  email: "john@example.com",
  age: 30,
  active: true,
};

const response = await api.put('/users/123', completeUserData);

// Process the successful response
console.log(`Status: ${response.status}`); // e.g., 200 OK
console.log('User completely updated:', response.data);

Advanced Usage

With Type Safety

// Define interfaces for full resource replacement
interface UserResource {
  id: number;
  name: string;
  email: string;
  age: number;
  active: boolean;
}

const fullUserUpdate: UserResource = {
  id: 123,
  name: "John Doe",
  email: "john.doe@example.com",
  age: 31,
  active: true,
};

const response = await api.put<UserResource>('/users/123', fullUserUpdate);

// TypeScript knows the exact shape of the response
const updatedUser = response.data;
console.log(updatedUser.name);

Custom Options

Add Headers

const response = await api.put('/users/123', fullUserUpdate, {
  headers: {
    'X-Update-Reason': 'Profile Revision',
    'Authorization': `Bearer ${yourAuthToken}`,
  },
});

Set Timeout

const response = await api.put('/users/123', fullUserUpdate, {
  timeout: 15000, // 15 seconds
});

Configure Retries

const response = await api.put('/users/123', fullUserUpdate, {
  retries: 3, // Retry up to 3 times
});

Error Handling

try {
  const response = await api.put('/users/123', fullUserUpdate);
  console.log('Update successful');
} catch (error) {
  console.error('Update failed:', error);
}

Full Example Scenario

import { SpeedcastApi } from 'speedcast-api';

const api = new SpeedcastApi({
  baseURL: 'https://api.example.com',
  defaultHeaders: {
    'Accept': 'application/json',
    'Content-Type': 'application/json'
  },
  timeout: 10000,
  retries: 2
});

async function updateEntireUserProfile() {
  try {
    // Complete profile replacement
    const completeProfile = {
      username: "johndoe",
      email: "john.doe@example.com",
      profile: {
        firstName: "John",
        lastName: "Doe",
        bio: "Software developer",
        skills: ["TypeScript", "React", "Node.js"],
      },
      settings: {
        theme: "dark",
        notifications: true,
      },
    };

    const response = await api.put<UserProfile>('/profile', completeProfile, {
      headers: {
        'Authorization': `Bearer ${yourAuthToken}`,
      }
    });

    // Replace entire local profile
    replaceEntireProfile(response.data);
    console.log('Profile completely updated:', response.data);
    
    return response.data;
  } catch (error) {
    console.error('Failed to update profile:', error);
    throw error;
  } finally {
    // Clean up operations
    clearFormState();
  }
}

Key Differences from PATCH

MethodPurposeExample
PUTReplaces the entire resource
api.put("/users/123", {
name: "New Name",
email: "new@email.com",
age: 30,
// All fields must be included
});
PATCHUpdates only specific fields
api.patch("/users/123", {
// Only update what's needed
name: "New Name",
});

Response Structure

The response from a PUT request has the following structure:

interface ApiResponse<T = any> {
  data: T;                           // Response data
  status: number;                    // HTTP status code
  statusText: string;                // HTTP status text
  headers: Record<string, string>;   // Response headers
}

💡 Quick Tips

  • PUT completely replaces the existing resource
  • Always include ALL required fields to prevent data loss
  • Use TypeScript interfaces to ensure all required fields are included
  • Common success status codes: 200 (OK) or 204 (No Content)
  • Use PATCH instead when you only need to update specific fields