May 27, 2026

SharePoint create folder: automate it with Python

Reading time :  
7
 min
Rebecca Pearson
Rebecca Pearson

SharePoint create folder: automate it with Python

If you've ever manually created folder structures in SharePoint for each new project, client, or quarter, you already know why automating SharePoint create folder operations matters. SharePoint is where enterprise documents live — over 200,000 organizations use SharePoint Online as part of Microsoft 365, according to Microsoft's 2025 Work Trend Index. Creating folders manually doesn't scale when your document management policy requires consistent hierarchies across hundreds of projects. The Microsoft Graph API gives you programmatic control over SharePoint's file system, and CodeWords lets you deploy folder-creation workflows as serverless endpoints that trigger from project management tools, Slack commands, or scheduled jobs.

Unlike generic AI automation posts, this guide shows real CodeWords workflows — not just theory.

TL;DR

  • SharePoint folders are created via the Microsoft Graph API's DriveItem endpoint — POST /drives/{drive-id}/items/{parent-id}/children.
  • Authentication requires Azure AD app registration with Sites.ReadWrite.All or Files.ReadWrite.All permissions.
  • CodeWords workflows can create entire folder hierarchies from templates, triggered by events in your project management stack.

What do you need to create SharePoint folders programmatically?

The machinery behind SharePoint folder creation has three moving parts: authentication (proving who you are), authorization (proving you're allowed), and the API call itself. Think of it as getting through airport security — you need ID (Azure AD credentials), a boarding pass (permissions/scopes), and then you can proceed to your gate (the API endpoint).

Requirements:

  • Azure AD app registration: Your automation's identity in Microsoft's ecosystem
  • API permissions: Sites.ReadWrite.All for site-level access, or Files.ReadWrite.All for broader file access
  • Site ID and Drive ID: Identifiers for the specific SharePoint site and document library
  • Microsoft Graph API: The unified REST API for all Microsoft 365 services

How do you set up Azure AD authentication?

Prerequisites

Step 1: Register an app in Azure AD

  1. Go to portal.azure.comAzure Active Directory → App registrations → New registration
  2. Name: "SharePoint Folder Automation"
  3. Supported account types: "Accounts in this organizational directory only" (single tenant)
  4. Redirect URI: Leave blank for daemon/service applications

Step 2: Add API permissions

  1. Navigate to your app → API permissions → Add a permission → Microsoft Graph
  2. Choose Application permissions (for server-to-server, no user interaction): - Sites.ReadWrite.All
  3. Click Grant admin consent (requires admin privileges)

Step 3: Create a client secret

  1. Go to Certificates & secrets → New client secret
  2. Set an expiration (recommend 24 months)
  3. Copy the secret value immediately — it's only shown once

Save three values: Tenant ID, Client ID (Application ID), and Client Secret.

How do you create a folder via the Microsoft Graph API?

Step 1: Authenticate and get an access token

import requests

def get_access_token(tenant_id: str, client_id: str, client_secret: str) -> str:
    url = f"https://login.microsoftonline.com/{tenant_id}/oauth2/v2.0/token"
    response = requests.post(url, data={
        "grant_type": "client_credentials",
        "client_id": client_id,
        "client_secret": client_secret,
        "scope": "https://graph.microsoft.com/.default",
    })
    response.raise_for_status()
    return response.json()["access_token"]

Step 2: Find your Site ID and Drive ID

def get_site_and_drive(token: str, site_hostname: str, site_path: str) -> tuple[str, str]:
    headers = {"Authorization": f"Bearer {token}"}

    site_url = f"https://graph.microsoft.com/v1.0/sites/{site_hostname}:{site_path}"
    site = requests.get(site_url, headers=headers).json()
    site_id = site["id"]

    drives_url = f"https://graph.microsoft.com/v1.0/sites/{site_id}/drives"
    drives = requests.get(drives_url, headers=headers).json()
    drive_id = drives["value"][0]["id"]

    return site_id, drive_id

Step 3: Create a folder

def create_folder(token: str, drive_id: str, parent_path: str, folder_name: str) -> dict:
    headers = {
        "Authorization": f"Bearer {token}",
        "Content-Type": "application/json",
    }

    if parent_path == "/":
        url = f"https://graph.microsoft.com/v1.0/drives/{drive_id}/root/children"
    else:
        url = f"https://graph.microsoft.com/v1.0/drives/{drive_id}/root:/{parent_path}:/children"

    body = {
        "name": folder_name,
        "folder": {},
        "@microsoft.graph.conflictBehavior": "fail",
    }

    response = requests.post(url, headers=headers, json=body)
    if response.status_code == 409:
        print(f"Folder '{folder_name}' already exists")
        return None
    response.raise_for_status()
    return response.json()

The @microsoft.graph.conflictBehavior parameter controls what happens if the folder already exists. Options: "fail" (return 409), "rename" (append a number), or "replace" (overwrite).

How do you create nested folder structures?

Real-world use cases rarely involve creating a single folder. You typically need a hierarchy — project folders with subfolders for deliverables, documentation, and resources.

Step 1: Define a folder template

PROJECT_TEMPLATE = {
    "01-Planning": ["Requirements", "Timeline", "Budget"],
    "02-Design": ["Wireframes", "Mockups", "Assets"],
    "03-Development": ["Source", "Tests", "Documentation"],
    "04-Delivery": ["Reports", "Sign-off", "Archive"],
}

Step 2: Create the hierarchy recursively

def create_folder_structure(token: str, drive_id: str, base_path: str,
                            project_name: str, template: dict):
    create_folder(token, drive_id, base_path, project_name)
    project_path = f"{base_path}/{project_name}" if base_path != "/" else project_name

    for parent_folder, subfolders in template.items():
        create_folder(token, drive_id, project_path, parent_folder)
        parent_path = f"{project_path}/{parent_folder}"
        for subfolder in subfolders:
            create_folder(token, drive_id, parent_path, subfolder)
            print(f"Created: {parent_path}/{subfolder}")

token = get_access_token(TENANT_ID, CLIENT_ID, CLIENT_SECRET)
_, drive_id = get_site_and_drive(token, "contoso.sharepoint.com", "/sites/Projects")
create_folder_structure(token, drive_id, "/", "Project-Alpha-2025", PROJECT_TEMPLATE)

This creates 16 folders (1 root + 4 parents + 12 subfolders) in a consistent structure.

How do you automate folder creation with CodeWords?

Inside CodeWords, wrap this logic in a microservice triggered by external events.

Step 1: Create a FastAPI endpoint

from fastapi import FastAPI
from pydantic import BaseModel

app = FastAPI()

class ProjectRequest(BaseModel):
    project_name: str
    client_name: str
    template: str = "standard"

@app.post("/create-project-folders")
def create_project_folders(req: ProjectRequest):
    token = get_access_token(TENANT_ID, CLIENT_ID, CLIENT_SECRET)
    _, drive_id = get_site_and_drive(token, SITE_HOST, SITE_PATH)

    templates = {
        "standard": PROJECT_TEMPLATE,
        "minimal": {"Documents": [], "Resources": []},
    }

    template = templates.get(req.template, PROJECT_TEMPLATE)
    folder_name = f"{req.client_name} - {req.project_name}"

    create_folder_structure(token, drive_id, "/", folder_name, template)
    return {"status": "created", "folder": folder_name}

Step 2: Connect triggers

Wire this endpoint to your project management workflow:

  • New Airtable record: Client onboarding form triggers folder creation
  • Slack command: /newproject Alpha-2025 creates the folder structure
  • Scheduled: Quarterly folders created automatically via CodeWords scheduling

What are the common errors and limits?

The Microsoft Graph API has specific constraints for SharePoint operations:

  • Rate limiting: 10,000 API calls per 10 minutes per app. For large folder structures, batch creation and add delays between calls.
  • Folder name restrictions: SharePoint prohibits ~ # % & * { } \ : < > ? / | and names starting/ending with spaces or periods. Validate names before API calls.
  • Path length: Maximum 400 characters for the full path. Deep nesting can hit this limit — keep folder names concise.
  • Permissions: Sites.ReadWrite.All is a broad permission. For production, consider using Sites.Selected with site-specific permissions for tighter access control.

According to Microsoft's Graph API documentation, throttled requests return a 429 status with a Retry-After header. Always implement retry logic:

import time

def create_folder_with_retry(token, drive_id, parent_path, folder_name, max_retries=3):
    for attempt in range(max_retries):
        response = create_folder(token, drive_id, parent_path, folder_name)
        if response is not None:
            return response
        time.sleep(2 ** attempt)
    return None

FAQs

Can I create folders in SharePoint without Azure AD?

No. The Microsoft Graph API requires Azure AD authentication. There's no anonymous or API-key-based access to SharePoint. For personal OneDrive (non-business), you can use delegated permissions with OAuth 2.0 user consent.

How do I create a folder inside a specific document library?

Each document library in SharePoint is a "drive." Use GET /sites/{site-id}/drives to list all document libraries, find the one you want by name, and use its id as the drive_id in your folder creation calls.

What's the difference between Sites.ReadWrite.All and Files.ReadWrite.All?

Sites.ReadWrite.All grants access to all SharePoint sites. Files.ReadWrite.All grants access to all files the app can access (including OneDrive). For SharePoint-only automation, Sites.ReadWrite.All is the appropriate scope.

Can I set folder permissions during creation?

Not in the same API call. Create the folder first, then set permissions via POST /drives/{drive-id}/items/{item-id}/invite with the desired role and recipients.

Conclusion

Automating SharePoint create folder operations replaces one of the most tedious parts of document management — the manual setup that happens every time a new project starts. The Microsoft Graph API makes it programmatic, and template-driven folder structures make it consistent. The real unlock is connecting folder creation to your existing project workflows so the right structure exists the moment a project is born, not three days later when someone remembers to set it up. Build your SharePoint automation in CodeWords — because folder structures shouldn't depend on someone's memory.

Contents
Ready to try CodeWords?
Get started free
Sign in
Sign in