# Sirv REST API - Python Examples

Use the Sirv [REST API](/help/rest-api/sirv-rest-api/) to perform more than 60 common tasks on your Sirv account.

Using an AI coding agent?

Install the [`sirv-api`](https://www.skills.sh/sirv/image-optimization-skill/sirv-api) skill, and your agent can call the Sirv API for you. Ask in plain words, such as “Upload the photos in /shoots/spring and tag them by product.” [See all 8 skills](/help/rest-api/sirv-skills-for-ai-agents/)

Visit the [REST API reference](/help/rest-api/reference/) for all methods.

## Connect to Sirv with Python

[Create an API client](https://app.sirv.com/settings/api) via your Sirv account, if you’ve not created one already. You’ll be given a client ID and client Secret.

Keep your client ID and secret in the SIRV\_CLIENT\_ID and SIRV\_CLIENT\_SECRET environment variables, not in the code. This script requests a token with them:

```python
import os
import requests
import json

url = 'https://api.sirv.com/v2/token'

payload = {
  'clientId': os.environ['SIRV_CLIENT_ID'],
  'clientSecret': os.environ['SIRV_CLIENT_SECRET']
}
headers = {'content-type': 'application/json'}

response = requests.request('POST', url, data=json.dumps(payload), headers=headers)

token = response.json()['token']
```

Now that you have a token, you can perform any of the more than 60 [API commands](/help/rest-api/reference/).

## Python upload example

Upload a file to your Sirv account.

-   Endpoint: `https://api.sirv.com/v2/files/upload`
-   Documentation: [Upload file](/help/rest-api/reference/upload-download/upload-file/)

Example upload script:

```python
url = 'https://api.sirv.com/v2/files/upload'

querystring = {'filename':'/path/to/uploaded-image.jpg'}

payload = open('/path/to/local-image.jpg', 'rb')

headers = {
 'content-type': 'image/jpeg',
 'authorization': 'Bearer %s' % token
}

response = requests.request('POST', url, data=payload, headers=headers, params=querystring)

print(response)
```

Including the connection to Sirv, to fetch a token, the script would look like this:

```python
import os
import requests
import json

# First, get a token

url = 'https://api.sirv.com/v2/token'

payload = {
  'clientId': os.environ['SIRV_CLIENT_ID'],
  'clientSecret': os.environ['SIRV_CLIENT_SECRET']
}

headers = {'content-type': 'application/json'}

response = requests.request('POST', url, data=json.dumps(payload), headers=headers)

token = response.json()['token']

# Now upload a file

url = 'https://api.sirv.com/v2/files/upload'

querystring = {'filename':'/path/to/uploaded-image.jpg'}

payload = open('/path/to/local-image.jpg', 'rb')

headers = {
  'content-type': 'image/jpeg',
  'authorization': 'Bearer %s' % token
}

response = requests.request('POST', url, data=payload, headers=headers, params=querystring)

print(response)
```

A response of 200 means the file was uploaded to your Sirv account.
