Sobes.tech
Junior — Middle

Do you have experience using PATCH and PUT methods when interacting with APIs or working with REST architecture?

sobes.tech AI

Answer from AI

Yes, the experience of using PATCH and PUT methods when working with REST API is quite common.

  • PUT is used for completely updating a resource. When calling PUT, usually a full representation of the object is sent, and the server replaces the existing resource with the sent one.
  • PATCH is used for partial updates of a resource, when only some fields need to be changed without affecting others.

For example, when updating a user profile:

// PUT - update the entire profile
let url = URL(string: "https://api.example.com/user/123")!
var request = URLRequest(url: url)
request.httpMethod = "PUT"
request.httpBody = try? JSONEncoder().encode(fullUserProfile)

// PATCH - update only the email
request.httpMethod = "PATCH"
let patchData = ["email": "newemail@example.com"]
request.httpBody = try? JSONSerialization.data(withJSONObject: patchData)

Using PATCH allows saving traffic and reducing the risk of overwriting data that should not be changed.