# Create or patch a thing with a specified ID

`PATCH /api/2/things/{thingId}`

Create or patch an existing thing specified by the `thingId` path parameter.

If the thing did not yet exist, it will be created.
For an existing thing, patching a thing will merge the provided request body with the existing thing values.
This makes it possible to change only some parts of a thing in single request without providing the full thing
structure in the request body.


### Patch a thing

With this resource it is possible to add, update or delete parts of an existing thing or to create the thing if it
does not yet exist.
The request body provided in *JSON merge patch* (RFC-7396) format will be merged with the existing thing.
Notice that the `null` value in the JSON body will delete the specified JSON key from the thing.
For further documentation of JSON merge patch see [RFC 7396](https://tools.ietf.org/html/rfc7396).


### Example
A Thing already exists with the following content:

```
{
  "definition": "com.acme:coffeebrewer:0.1.0",
  "attributes": {
    "manufacturer": "ACME demo corp.",
    "location": "Berlin, main floor",
    "serialno": "42",
    "model": "Speaking coffee machine"
  },
  "features": {
    "coffee-brewer": {
      "definition": ["com.acme:coffeebrewer:0.1.0"],
      "properties": {
        "brewed-coffees": 0
      }
    },
    "water-tank": {
      "properties": {
        "configuration": {
          "smartMode": true,
          "brewingTemp": 87,
          "tempToHold": 44,
          "timeoutSeconds": 6000
        },
        "status": {
          "waterAmount": 731,
          "temperature": 44
        }
      }
    }
  }
}
```

To make changes that only affect parts of the existing thing, e.g. add some attribute and delete a
specific feature property, the content of the request body could look like this:

```
{
  "attributes": {
    "manufacturingYear": "2020"
  },
  "features": {
    "water-tank": {
      "properties": {
        "configuration": {
          "smartMode": null,
          "tempToHold": 50,
        }
      }
    }
  }
}
```

The request body will be merged with the existing thing and the result will be the following thing:

```
{
  "definition": "com.acme:coffeebrewer:0.1.0",
  "attributes": {
    "manufacturer": "ACME demo corp.",
    "manufacturingYear": "2020",
    "location": "Berlin, main floor",
    "serialno": "42",
    "model": "Speaking coffee machine"
  },
  "features": {
    "coffee-brewer": {
      "definition": ["com.acme:coffeebrewer:0.1.0"],
      "properties": {
        "brewed-coffees": 0
      }
    },
    "water-tank": {
      "properties": {
        "configuration": {
          "brewingTemp": 87,
          "tempToHold": 50,
          "timeoutSeconds": 6000
        },
        "status": {
          "waterAmount": 731,
          "temperature": 44
        }
      }
    }
  }
}
```

### Permissions for patching an existing Thing

For updating an existing thing, the authorized subject needs **WRITE** permission on those parts of the thing
that are affected by the merge update.

For example, to successfully execute the above example the authorized subject needs to have unrestricted
*WRITE* permissions on all affected paths of the JSON merge patch: `attributes/manufacturingYear`,
`features/water-tank/properties/configuration/smartMode`,
`features/water-tank/properties/configuration/tempToHold`. The *WRITE* permission must not be revoked on any
level further down the hierarchy. Consequently it is also sufficient for the authorized subject to have
unrestricted *WRITE* permission at root level or unrestricted *WRITE* permission at `/attributes` and
`/features` etc.

Authentication (security requirement alternatives):

```json
[
  {
    "OpenIDConnect": []
  },
  {
    "NginxBasic": []
  },
  {
    "Bearer": []
  }
]
```

- OpenIDConnect: openIdConnect. OpenID Connect Discovery URL. The placeholder is replaced by Swagger UI when configured.
- NginxBasic: http (basic). Eclipse Ditto sandbox demo user (demo1 ... demo9) + password (demo)
- Bearer: http (bearer). A JSON Web Token issued by a supported OAuth 2.0 Identity Provider.

Parameters:

- `thingId` (path, string, required) - The ID of a thing needs to follow the namespaced entity ID notation (see [Ditto documentation on namespaced entity IDs](https://www.eclipse.dev/ditto/basic-namespaces-and-names.html#namespaced-id)).
  Type: string

- `If-Match` (header, string, optional) - The `If-Match` header, which has to conform to RFC-7232 (Conditional Requests). Common usages are:
  * optimistic locking by specifying the `ETag` from a previous GET response, e.g. `If-Match: "rev:4711"`
  * retrieving or modifying a resource only if it already exists, e.g. `If-Match: *`
  Type: string

- `If-None-Match` (header, string, optional) - The `If-None-Match` header, which has to conform to RFC-7232 (Conditional Requests). A common usage scenario is to modify a resource only if it does not yet exist, thus to create it, by specifying `If-None-Match: *`.
  Type: string

- `if-equal` (header, string, optional) - The `if-equal` header can take the values 'update' (which is the default if omitted), 'skip' or 'skip-minimizing-merge'. If 'update' is defined, the entity will always be updated, even if it is equal before the update. If 'skip' is defined, the entity not be updated if it is equal before the update.  In this case a 'Precondition Failed' 412 status is returned. If 'skip-minimizing-merge' is defined, the entity will not be updated if it is equal before the update.   In this case a 'Precondition Failed' 412 status is returned. Additionally, merge/patch commands will be minimized to only the fields which actually changed, compared to the current state of the entity.
  Type: string
  
  enum: ["update","skip","skip-minimizing-merge"]

- `put-metadata` (header, Array<object>, optional) - The `put-metadata` header, which sets Metadata information in the Thing.
  Type: Array<object>
  
  An array of objects containing metadata to apply.
  
  Items:
    Type: object
    
    Object containing a `key` where to apply the metadata and a `value` with the metadata value to apply.
    
    Additional properties: 
      Type: any
      
      - `key` (optional)
        Type: string
        
        The JsonPointer to set the metadata `value` to. May start with `*/<key>` in order to apply the metadata to all affected JSON leaves.
      
      - `value` (optional)
        Type: any
        
        The arbitrary JSON value to set as metadata.

- `delete-metadata` (header, string, optional) - The `delete-metadata` header, which deletes Metadata of the Thing.
  Type: string
  
  A string of comma separated JsonPointers to delete from the Metadata of the Thing.

- `requested-acks` (query, string, optional) - Contains the "requested acknowledgements" for this modifying request as comma separated list. The HTTP call will
block until all requested acknowledgements were aggregated or will time out based on the specified `timeout`
parameter.

The default (if omitted) requested acks is `requested-acks=twin-persisted` which will block the
HTTP call until the change was persited to the twin.
  Type: string

- `timeout` (query, string, optional) - Defines how long the backend should wait for completion of the request, e.g. applied when waiting for requested
acknowledgements via the `requested-acks` param. Can be specified without unit (then seconds are assumed) or
together with `s`, `ms` or `m` unit. Example: `42s`, `1m`.

The default (if omitted) and maximum timeout is `60s`. A value of `0` applies fire and forget semantics for
the command resulting in setting `response-required=false`.
  Type: string

- `response-required` (query, boolean, optional) - Defines whether a response is required to the API call or not - if set to `false` the response will directly
sent back with a status code of `202` (Accepted).

The default (if ommited) response is `true`.
  Type: boolean

- `condition` (query, string, optional) - Defines that the request should only be processed if the given condition is met. The condition can be specified using RQL syntax. 
#### Examples
E.g. if the temperature is not 23.9 update it to 23.9:
* ```PUT /api/2/things/{thingId}/features/temperature/properties/value?condition=ne(features/temperature/properties/value,23.9)```

   `body: 23.9`

Further example conditions:
* ```?condition=eq(features/temperature/properties/unit,"Celsius")```
* ```?condition=ge(features/temperature/properties/lastModified,"2021-08-22T19:45:00Z")```
* ```?condition=gt(_modified,"2021-08-05T12:17:00Z")```
* ```?condition=exists(features/temperature/properties/value)```
* ```?condition=empty(features/temperature/properties/value)```
* ```?condition=and(gt(features/temperature/properties/value,18.5),lt(features/temperature/properties/value,25.2))```
* ```?condition=or(gt(features/temperature/properties/value,18.5),not(exists(features/temperature/properties/value))```
  Type: string

- `channel` (query, string, optional) - Defines to which channel to route the command: `twin` (digital twin) or `live` (the device).
* If setting the channel parameter is omitted, the `twin` channel is set by default and the command is routed to the persisted representation of a thing in Eclipse Ditto.
* When using the `live` channel, the command/message is sent towards the device.
  Type: string
  
  enum: ["twin","live"]

Request body: application/merge-patch+json

JSON representation of the thing to be patched.

Type: PatchThing

Schema: [PatchThing](https://sourcey-ditto.pages.dev/http-api-doc/models/patchthing.md)

- `thingId` (required)
  Type: string
  
  Unique identifier representing the thing

- `policyId` (required)
  Type: string
  
  The ID of the policy which controls the access to this thing. policies are managed by resource `/policies/{policyId}`

- `definition` (optional)
  Reference: [Definition](https://sourcey-ditto.pages.dev/http-api-doc/models/definition.md); Type: Definition
  
  A single fully qualified identifier of a definition in the form '<namespace>:<name>:<version>' or a valid HTTP(s) URL
  
  pattern: "([_a-zA-Z0-9\\-.]+):([_a-zA-Z0-9\\-.]+):([_a-zA-Z0-9\\-.]+)"

- `attributes` (optional)
  Reference: [Attributes](https://sourcey-ditto.pages.dev/http-api-doc/models/attributes.md); Type: Attributes
  
  An arbitrary JSON object describing the attributes of a thing.

- `features` (optional)
  Reference: [Features](https://sourcey-ditto.pages.dev/http-api-doc/models/features.md); Type: Features
  
  List of features where the key represents the `featureId` of each feature.
  The `featureId` key must be unique in the list.

```json
{
  "attributes": {
    "manufacturingYear": "2020"
  },
  "features": {
    "water-tank": {
      "properties": {
        "configuration": {
          "smartMode": null,
          "tempToHold": 50
        }
      }
    }
  }
}
```

Responses:

- 201: The thing was successfully created.

Content type: application/json

Type: Thing

Schema: [Thing](https://sourcey-ditto.pages.dev/http-api-doc/models/thing.md)

- `thingId` (required)
  Type: string
  
  Unique identifier representing the thing

- `policyId` (required)
  Type: string
  
  The ID of the policy which controls the access to this thing. policies are managed by resource `/policies/{policyId}`

- `definition` (optional)
  Reference: [Definition](https://sourcey-ditto.pages.dev/http-api-doc/models/definition.md); Type: Definition
  
  A single fully qualified identifier of a definition in the form '<namespace>:<name>:<version>' or a valid HTTP(s) URL
  
  pattern: "([_a-zA-Z0-9\\-.]+):([_a-zA-Z0-9\\-.]+):([_a-zA-Z0-9\\-.]+)"

- `attributes` (optional)
  Reference: [Attributes](https://sourcey-ditto.pages.dev/http-api-doc/models/attributes.md); Type: Attributes
  
  An arbitrary JSON object describing the attributes of a thing.

- `features` (optional)
  Reference: [Features](https://sourcey-ditto.pages.dev/http-api-doc/models/features.md); Type: Features
  
  List of features where the key represents the `featureId` of each feature.
  The `featureId` key must be unique in the list.

- `_revision` (optional)
  Type: string
  
  _(read-only)_ The revision is a counter which is incremented on each modification of a Thing. This field
  is not returned by default but must be selected explicitly.

- `_created` (optional)
  Type: string
  
  _(read-only)_ The created timestamp of the Thing in ISO-8601 UTC format. The timestamp is set on creation
  of a Thing. This field is not returned by default but must be selected explicitly.

- `_modified` (optional)
  Type: string
  
  _(read-only)_ The modified timestamp of the Thing in ISO-8601 UTC format. The timestamp is set on each
  modification of a Thing. This field is not returned by default but must be selected explicitly.

- `_metadata` (optional)
  Type: object
  
  _(read-only)_ The Metadata of the Thing. This field is not returned by default but must be selected explicitly.

- 204: The thing was successfully patched.

- 400: The request could not be completed. Possible reasons:

  * the JSON body of the thing to be patched is invalid
  * the JSON body of the thing to be patched contains a `thingId` which does not match the ID in the path

Content type: application/json

Type: AdvancedError

Schema: [AdvancedError](https://sourcey-ditto.pages.dev/http-api-doc/models/advancederror.md)

- `status` (required)
  Type: integer
  
  The HTTP status of the error

- `error` (required)
  Type: string
  
  The error code of the occurred exception

- `message` (required)
  Type: string
  
  The message of the error - what went wrong

- `description` (optional)
  Type: string
  
  A description how to fix the error or more details

- `href` (optional)
  Type: string
  
  A link to further information about the error and how to fix it

- 401: The request could not be completed due to missing authentication.

Content type: application/json

Type: AdvancedError

Schema: [AdvancedError](https://sourcey-ditto.pages.dev/http-api-doc/models/advancederror.md)

- `status` (required)
  Type: integer
  
  The HTTP status of the error

- `error` (required)
  Type: string
  
  The error code of the occurred exception

- `message` (required)
  Type: string
  
  The message of the error - what went wrong

- `description` (optional)
  Type: string
  
  A description how to fix the error or more details

- `href` (optional)
  Type: string
  
  A link to further information about the error and how to fix it

- 403: The request could not be completed. Possible reasons:
  * the caller would not have access to the thing after creating it with the given policy
  * the caller has insufficient permissions.
    For modifying an existing thing, an unrestricted `WRITE` permission on the thing's root resource is required.

Content type: application/json

Type: AdvancedError

Schema: [AdvancedError](https://sourcey-ditto.pages.dev/http-api-doc/models/advancederror.md)

- `status` (required)
  Type: integer
  
  The HTTP status of the error

- `error` (required)
  Type: string
  
  The error code of the occurred exception

- `message` (required)
  Type: string
  
  The message of the error - what went wrong

- `description` (optional)
  Type: string
  
  A description how to fix the error or more details

- `href` (optional)
  Type: string
  
  A link to further information about the error and how to fix it

- 404: The request could not be completed. Possible reasons:
  * the referenced thing does not exist.
  * the caller has insufficient permissions to read the referenced thing.
  * the policy that should be copied does not exist.

Content type: application/json

Type: AdvancedError

Schema: [AdvancedError](https://sourcey-ditto.pages.dev/http-api-doc/models/advancederror.md)

- `status` (required)
  Type: integer
  
  The HTTP status of the error

- `error` (required)
  Type: string
  
  The error code of the occurred exception

- `message` (required)
  Type: string
  
  The message of the error - what went wrong

- `description` (optional)
  Type: string
  
  A description how to fix the error or more details

- `href` (optional)
  Type: string
  
  A link to further information about the error and how to fix it

- 412: A precondition for reading or writing the (sub-)resource failed. This will happen for write requests, if you
specified an If-Match or If-None-Match header, which fails the precondition check against the current ETag of
the (sub-)resource. For read requests, this error may only happen for a failing If-Match header. In case of a
failing If-None-Match header for a read request, status 304 will be returned instead.

Content type: application/json

Type: AdvancedError

Schema: [AdvancedError](https://sourcey-ditto.pages.dev/http-api-doc/models/advancederror.md)

- `status` (required)
  Type: integer
  
  The HTTP status of the error

- `error` (required)
  Type: string
  
  The error code of the occurred exception

- `message` (required)
  Type: string
  
  The message of the error - what went wrong

- `description` (optional)
  Type: string
  
  A description how to fix the error or more details

- `href` (optional)
  Type: string
  
  A link to further information about the error and how to fix it

- 413: The created or modified entity is larger than the accepted limit of 100 kB.

Content type: application/json

Type: AdvancedError

Schema: [AdvancedError](https://sourcey-ditto.pages.dev/http-api-doc/models/advancederror.md)

- `status` (required)
  Type: integer
  
  The HTTP status of the error

- `error` (required)
  Type: string
  
  The error code of the occurred exception

- `message` (required)
  Type: string
  
  The message of the error - what went wrong

- `description` (optional)
  Type: string
  
  A description how to fix the error or more details

- `href` (optional)
  Type: string
  
  A link to further information about the error and how to fix it

- 424: One or more acknowledgement requests in the parameter `requested-acks`
were not fulfilled.

Content type: application/json

Type: any

Example:

```json
{
  "acknowledgementLabel1": {
    "status": 200,
    "payload": "OK"
  },
  "acknnowledgementLabelN": {
    "status": 403,
    "payload": "Forbidden"
  }
}
```

- `acknowledgementLabel1` (optional)
  Type: any
  
  Example:
  
  ```json
  {
    "status": 200,
    "payload": "OK"
  }
  ```
  
  - `status` (required)
    Type: integer
    
    The HTTP status of the acknowledgement
  
  - `payload` (optional)
    Type: object | string | number | array | boolean
    
    The payload of the acknowledgement
    
    oneOf:
      Type: object
    
      Type: string
    
      Type: number
    
      Type: array
    
      Type: boolean

## Examples

### cURL

```bash
curl -X PATCH 'https://ditto.eclipseprojects.io/api/2/things/string' \
  -H 'Authorization: Bearer YOUR_TOKEN' \
  -H 'Content-Type: application/merge-patch+json' \
  --data-raw '{
  "attributes": {
    "manufacturingYear": "2020"
  },
  "features": {
    "water-tank": {
      "properties": {
        "configuration": {
          "smartMode": null,
          "tempToHold": 50
        }
      }
    }
  }
}'
```

### JavaScript

```javascript
const body = `{
  "attributes": {
    "manufacturingYear": "2020"
  },
  "features": {
    "water-tank": {
      "properties": {
        "configuration": {
          "smartMode": null,
          "tempToHold": 50
        }
      }
    }
  }
}`;

const response = await fetch('https://ditto.eclipseprojects.io/api/2/things/string', {
  method: 'PATCH',
  headers: {
    'Authorization': 'Bearer YOUR_TOKEN',
    'Content-Type': 'application/merge-patch+json',
  },
  body,
});

const data = await response.text();
```

### Python

```python
import requests

body = '''{
  "attributes": {
    "manufacturingYear": "2020"
  },
  "features": {
    "water-tank": {
      "properties": {
        "configuration": {
          "smartMode": null,
          "tempToHold": 50
        }
      }
    }
  }
}'''

response = requests.patch(
    'https://ditto.eclipseprojects.io/api/2/things/string',
    data=body.encode('utf-8'),
    headers={
        'Authorization': 'Bearer YOUR_TOKEN',
        'Content-Type': 'application/merge-patch+json',
    },
)
print(response.text)
```
