Middle
What are the differences between the basic HTTP methods GET, POST, PUT, PATCH, DELETE?
sobes.tech AI
Answer from AI
HTTP methods define the type of operation the client wants to perform on the server:
- GET — requests data from the server. Does not change the state, is idempotent and safe. Used for retrieving information.
- POST — sends data to the server to create a new resource or perform an operation. Not idempotent, may change the state.
- PUT — replaces an existing resource or creates it if it does not exist. Idempotent, meaning repeated requests with the same data give the same result.
- PATCH — partially updates a resource, changing only specified fields. Not necessarily idempotent, depends on implementation.
- DELETE — deletes a resource. Idempotent, repeated deletion of the same resource does not change the result.
Example in C# using HttpClient:
var client = new HttpClient();
// GET
var response = await client.GetAsync("https://api.example.com/items/1");
// POST
var content = new StringContent(jsonData, Encoding.UTF8, "application/json");
response = await client.PostAsync("https://api.example.com/items", content);
// PUT
response = await client.PutAsync("https://api.example.com/items/1", content);
// PATCH (using HttpMethod)
var method = new HttpMethod("PATCH");
var request = new HttpRequestMessage(method, "https://api.example.com/items/1") { Content = content };
response = await client.SendAsync(request);
// DELETE
response = await client.DeleteAsync("https://api.example.com/items/1");