File Management

Read File

Introduction

If a ReadSingleFileRequest is passed, reads that file from the project. If a ReadAllFilesRequest is passed, reads all files in the project.

Request

An array list of files from the project requested. The /files/read API accepts requests in the following format:

ReadFilesRequest Model - Request to read all files from a project or just one (if the name is provided).
projectId integer
required

Id of the project that contains the file.
name string
The name of the file to read.
codeSourceId string
Name of the environment that's creating the request.
Example
{
  "projectId": 0,
  "name": "string",
  "codeSourceId": "string"
}

Responses

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

200 Success

ProjectFilesResponse Model - Response received when creating or reading project files.
files ProjectFile Array
List of project file information.
success boolean
Indicate if the API request was successful.
errors string Array
List of errors with the API call.
Example
{
  "files": [
    {
      "id": 0,
      "projectId": 0,
      "name": "string",
      "content": "string",
      "modified": "2021-11-26T15:18:27.693Z",
      "open": true,
      "isLibrary": true
    }
  ],
  "success": true,
  "errors": [
    "string"
  ]
}
ProjectFile Model - File for a project.
id integer
ID of the project file. This can also be null.
projectId integer
ID of the project.
name string
Name of a project file.
content string
Contents of the project file.
modified string($date-time)
DateTime project file was modified.
open boolean
Indicates if the project file is open or not.
isLibrary boolean
Indicates if the project file is a library or not. It's always false in live/read and backtest/read.
Example
{
  "id": 0,
  "projectId": 0,
  "name": "string",
  "content": "string",
  "modified": "2021-11-26T15:18:27.693Z",
  "open": true,
  "isLibrary": true
}

401 Authentication Error

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: