Junior — Middle
What is the purpose and features of the HTTP PATCH method?
sobes.tech AI
Answer from AI
The HTTP PATCH method is used for partial updates of a resource on the server. Unlike PUT, which usually replaces the entire resource, PATCH allows sending only the fields that need to be changed.
Features of PATCH:
- Partial update: only specified fields are changed.
- Idempotency is not guaranteed, unlike PUT.
- The request body contains instructions for modification, often in JSON format.
Example of usage in Flutter with the http package:
import 'package:http/http.dart' as http;
Future<void> updateUserName(String userId, String newName) async {
final url = Uri.parse('https://api.example.com/users/$userId');
final response = await http.patch(
url,
headers: {'Content-Type': 'application/json'},
body: '{"name": "$newName"}',
);
if (response.statusCode == 200) {
print('User updated successfully');
} else {
print('Failed to update user');
}
}