File Management

Delete File

Introduction

Apply a patch (unified diff) to a file in a project.

Request

Project Id and patch content in unified diff format. The /files/patch API accepts requests in the following format:

PatchFileRequest Model - Request to apply a patch (unified diff) to a file in a project.
projectId integer
required

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

A patch string in **unified diff format** (as produced by `git diff`). It specifies changes to apply to one or more files in the project. **Required format:** - Must include `diff --git a/filename b/filename` header - Must include `index` line (can use placeholder hashes like `1234567..abcdefg`) - Must include `--- a/filename` and `+++ b/filename` lines - Must include `@@` hunk headers with line numbers and context counts - Include context lines before and after changes when possible - Use exact line content from the file (whitespace sensitive) **CRITICAL: The patch must match the EXACT file content including:** - Exact whitespace (spaces vs tabs) - Exact line endings - Exact indentation - All characters must match precisely **Recommended approach:** 1. Read the current file content first 2. Use 3+ lines of context before and after the change 3. Copy exact text from the file for context lines 4. Only modify the specific line(s) that need changing See examples for the complete structure required. .
codeSourceId string
Name of the environment that's creating the request.
Example
{
  "projectId": 0,
  "patch": "string",
  "codeSourceId": "string"
}

Responses

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

200 Success

RestResponse Model - Base API response class for the QuantConnect API.
success boolean
Indicate if the API request was successful.
errors string Array
List of errors with the API call.
Example
{
  "success": true,
  "errors": [
    "string"
  ]
}

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: