File Management

Update File

Introduction

If an UpdateProjectFileNameRequest is passed, update the name of a file. If a UpdateProjectFileContentsRequest is passed, update the contents of a file.

Request

Information about the file to update along with the new properties to set. The /files/update API accepts requests in the following format:

UpdateFileNameRequest Model - Request to update the name of a file.
projectId integer
required

Id of the project that contains the file.
name string
required

The current name of the file.
newName string
required

The new name for the file.
codeSourceId string
Name of the environment that's creating the request.
Example
{
  "projectId": 0,
  "name": "string",
  "newName": "string",
  "codeSourceId": "string"
}
UpdateFileContentsRequest Model - Request to update the contents of a file.
projectId integer
required

Id of the project that contains the file.
name string
required

The name of the file to update.
content string
required

The new contents of the file.
codeSourceId string
Name of the environment that's creating the request.
Example
{
  "projectId": 0,
  "name": "string",
  "content": "string",
  "codeSourceId": "string"
}

Responses

The /files/update API provides a response in the following format:

200 Success

401 Authentication Error

Base API response class.
UnauthorizedError Model - Unauthorized response from the API. Key is missing, invalid, or timestamp is too old for hash.
www_authenticate string
Header

Examples

The following example demonstates creating, reading, updating, and deleting a file through the cloud API.

from base64 import b64encode
from hashlib import sha256
from time import time
from requests import get, post
BASE_URL = 'https://www.quantconnect.com/api/v2/'

# You need to replace these with your actual credentials.
# You can request your credentials at https://www.quantconnect.com/settings/
# You can find our organization ID at https://www.quantconnect.com/organization/ 
USER_ID = 0
API_TOKEN = '____'
ORGANIZATION_ID = '____'

def get_headers():
    # Get timestamp
    timestamp = f'{int(time())}'
    time_stamped_token = f'{API_TOKEN}:{timestamp}'.encode('utf-8')

    # Get hased API token
    hashed_token = sha256(time_stamped_token).hexdigest()
    authentication = f'{USER_ID}:{hashed_token}'.encode('utf-8')
    authentication = b64encode(authentication).decode('ascii')

    # Create headers dictionary.
    return {
        'Authorization': f'Basic {authentication}',
        'Timestamp': timestamp
    }

# Authenticate to verify credentials
response = post(f'{BASE_URL}/authenticate', headers = get_headers())
print(response.json())

# --------------------


# The project ID of the project to manage its files
project_id = 12345678

### Create File
# Send a POST request to the /files/create endpoint to create a new file
response = post(f'{BASE_URL}/files/create', headers=get_headers(), json={
    "projectId": project_id,  # ID of the project
    "name": "utils.py",  # Name of the new file
    "content": '''
# region imports
from AlgorithmImports import *
# endregion

class Project(QCAlgorithm):

    def Initialize(self):
        self.AddEquity("SPY", Resolution.Minute)
'''  # Content of the file (Python code)
})
# Parse the JSON response into python managable dict
result = response.json()
# Check if the request was successful and print the result
if result['success']:
    print("File Created Successfully:")
    print(result)

### Read File
# Prepare data payload to read files in the project
payload = {
    "projectId": project_id,  # ID of the project
    "includeLibraries": True  # Include library files in the response
}
# Send a POST request to the /files/read endpoint to read files
response = post(f'{BASE_URL}/files/read', headers=get_headers(), json=payload)
# Parse the JSON response into python managable dict
result = response.json()
# Extract filename and content from the first file in the response
fileName = result['files'][0]['name']
content = result['files'][0]['content']
# Check if the request was successful and print the content
if result['success']:
    print("File Content:")
    print(content)

### Update File Contents
# Modify the content by replacing "SPY" with "TSLA"
content = content.replace("SPY", "TSLA")
# Send a POST request to the /files/update endpoint to update the file content
response = post(f'{BASE_URL}/files/update', headers=get_headers(), json={
    "projectId": project_id,  # ID of the project
    "name": "utils.py",  # Name of the file to update
    "content": content  # Updated content
})
# Parse the JSON response into python managable dict
result = response.json()
# Check if the request was successful and print the result
if result['success']:
    print("File Updated Successfully:")
    print(result)

### Rename File
# Send a POST request to the /files/update endpoint to rename the file
response = post(f'{BASE_URL}/files/update', headers=get_headers(), json={
    "projectId": project_id,  # ID of the project
    "name": "utils.py",  # Current name of the file
    "newName": "utils2.py"  # New name for the file
})
# Parse the JSON response into python managable dict
result = response.json()
# Check if the request was successful and print the result
if result['success']:
    print("File Renamed Successfully:")
    print(result)

### Delete File
# Prepare data payload to delete the file
payload = {
    "projectId": project_id,  # ID of the project
    "name": "utils2.py"  # Name of the file to delete
}
# Send a POST request to the /files/delete endpoint to delete the file
response = post(f'{BASE_URL}/files/delete', headers=get_headers(), json=payload)
# Parse the JSON response into python managable dict
result = response.json()
# Check if the request was successful and print the result
if result['success']:
    print("File Deleted Successfully:")
    print(result)

You can also see our Videos. You can also get in touch with us via Discord.

Did you find this page helpful?

Contribute to the documentation: