How to Create Folders with SharePoint API: REST, Graph, and Agent Workspaces
Creating folders across SharePoint environments requires choosing between legacy REST endpoints and modern Microsoft Graph calls. While REST relies on server-relative URLs and form digests, Graph uses drive item hierarchies and folder facets. For AI agent teams, automating directory provisioning and syncing SharePoint document libraries into indexed Fast.io workspaces eliminates the latency and token waste of recursive API traversal.
How SharePoint REST API and Microsoft Graph Compare for Folder Creation
Engineering teams automating enterprise document management face an immediate split: SharePoint provides two distinct API surfaces for creating folders, each with incompatible authentication requirements, URL conventions, and payload structures. Directly driving directory structures through these interfaces presents friction for automated systems. Microsoft Graph represents the unified endpoint across Microsoft 365, while the SharePoint REST API (/_api/web/) remains necessary for certain on-premises deployments, legacy SharePoint add-ins, and classic SharePoint list structures.
Creating folders in SharePoint via API can be executed using the SharePoint REST endpoint _api/web/folders/add or through Microsoft Graph drive item creation with a folder facet.
The two approaches approach folder creation from different object models. Microsoft Graph treats document libraries as drives and folders as drive items with a specific facet. SharePoint REST treats the site collection as a web object (SP.Web) and manages folders through server-relative filesystem paths.
Side-by-Side Request Payloads
When creating a folder, Microsoft Graph requires specifying the folder name and an empty folder facet object in JSON:
{
"name": "Project-Alpha",
"folder": {},
"@microsoft.graph.conflictBehavior": "rename"
}
In contrast, the SharePoint REST API requires specifying the full server-relative URL path along with the OData type annotation:
{
"__metadata": { "type": "SP.Folder" },
"ServerRelativeUrl": "/sites/Engineering/Shared Documents/Project-Alpha"
}
Architectural Differences
The choice between Microsoft Graph and SharePoint REST determines your authentication requirements, endpoint structure, and error-handling routines:
Modern cloud automation standardizes on Microsoft Graph because it provides uniform JSON responses, simplified OAuth scopes, and predictable pagination across Microsoft 365 services.
Related guides
- How to List Files with SharePoint API: REST, Graph, and Agent WorkspacesListing files across SharePoint environments requires choosing between legacy REST endpoints and Microsoft Graph drive...
- How to List Files with OneDrive API: Graph Endpoints and Agent WorkspacesThe OneDrive API, integrated into Microsoft Graph, lists drive items using the /me/drive/root/children or...
- ChatGPT SharePoint Connector: Enterprise Setup vs. Fast.io MCP WorkspacesConnecting ChatGPT to SharePoint document libraries gives conversational models access to enterprise knowledge. While...
- How to Download Files via OneDrive API: Microsoft Graph GuideDownloading a file via the OneDrive API requires requesting the binary stream from a driveItem content endpoint using...
- Connecting AutoGen Multi-Agent Systems to SharePoint: Architecture and SetupAn AutoGen SharePoint connector enables Microsoft AutoGen agent teams to authenticate against Microsoft Graph and query...
- How to Connect ChatGPT to SharePoint Document LibrariesConnecting ChatGPT to SharePoint allows conversational AI models to query enterprise document libraries through...
More on this subject: Agent File and Document Workflows (269 guides)
How to Create Folders in Document Libraries Using Microsoft Graph
To create a folder in a SharePoint document library using Microsoft Graph, your application makes an HTTP POST request to the children collection of the parent drive item. When creating a folder via Microsoft Graph, successful calls return a 201 Created response code and a DriveItem resource.
Step 1: Resolve the Site and Drive Identifiers
Microsoft Graph addresses SharePoint resources hierarchically. Before creating a folder, you must obtain the site ID and drive ID. Query the site by its hostname and relative path:
GET https://graph.microsoft.com/v1.0/sites/{hostname}:/sites/{site-path}
Authorization: Bearer {token}
Accept: application/json
The response returns a composite site identifier formatted as {hostname},{spsite-id},{spweb-id}. With the site ID, query the site's document libraries:
GET https://graph.microsoft.com/v1.0/sites/{site-id}/drives
Authorization: Bearer {token}
Accept: application/json
Locate the drive corresponding to your target document library (such as the default Documents or Shared Documents library) and copy its id.
Step 2: Issue the Folder Creation POST Request
To create a folder in the root of the document library, post to the /root/children endpoint:
POST https://graph.microsoft.com/v1.0/sites/{site-id}/drives/{drive-id}/root/children
Authorization: Bearer {token}
Content-Type: application/json
{
"name": "Quarterly-Reports",
"folder": {},
"@microsoft.graph.conflictBehavior": "rename"
}
To create a nested subfolder within an existing folder, replace /root with /items/{parent-item-id}:
POST https://graph.microsoft.com/v1.0/sites/{site-id}/drives/{drive-id}/items/{parent-item-id}/children
Authorization: Bearer {token}
Content-Type: application/json
{
"name": "2026-Q3",
"folder": {},
"@microsoft.graph.conflictBehavior": "fail"
}
Conflict Resolution Modes
The @microsoft.graph.conflictBehavior property determines how Microsoft Graph behaves if a folder with the specified name already exists:
rename: The service appends an incrementing number to the name (for example,Quarterly-Reports 1). This is the safest setting for unattended background jobs.fail: The API aborts the creation and returns an HTTP 409 Conflict error. Use this when duplicate names indicate a concurrency defect.replace: For folders,replacemerges the folder if it already exists, returning the existing drive item.
Implementation Example in Python
The following Python function creates a folder in a document library with automatic token passing:
pip install requests
import requests
def create_graph_folder(
access_token: str,
site_id: str,
drive_id: str,
folder_name: str,
parent_item_id: str = "root",
conflict_behavior: str = "rename",
) -> dict:
"""Create a folder in a SharePoint document library using Microsoft Graph."""
if parent_item_id == "root":
url = f"https://graph.microsoft.com/v1.0/sites/{site_id}/drives/{drive_id}/root/children"
else:
url = f"https://graph.microsoft.com/v1.0/sites/{site_id}/drives/{drive_id}/items/{parent_item_id}/children"
headers = {
"Authorization": f"Bearer {access_token}",
"Content-Type": "application/json",
}
payload = {
"name": folder_name,
"folder": {},
"@microsoft.graph.conflictBehavior": conflict_behavior,
}
response = requests.post(url, headers=headers, json=payload, timeout=30)
response.raise_for_status()
return response.json()
A successful creation returns HTTP 201 Created with the full drive item representation, including its unique id, webUrl, and createdDateTime.
How to Create Folders in Document Libraries and Lists with SharePoint REST
The legacy SharePoint REST API provides direct endpoints under the site collection web context (/_api/web/). While Microsoft Graph is preferred for modern applications, SharePoint REST remains relevant when integrating with legacy systems or when working with custom SharePoint lists rather than document libraries.
Method 1: Using the Web Folders Collection
The primary REST approach posts directly to the _api/web/folders collection. This endpoint requires specifying the full server-relative URL of the new folder:
POST https://{tenant}.sharepoint.com/sites/{site}/_api/web/folders
Authorization: Bearer {token}
Accept: application/json;odata=verbose
Content-Type: application/json;odata=verbose
X-RequestDigest: {digest}
{
"__metadata": { "type": "SP.Folder" },
"ServerRelativeUrl": "/sites/Engineering/Shared Documents/SubfolderName"
}
The ServerRelativeUrl must begin with the site path (for example, /sites/Engineering/) followed by the document library name and the new folder name. If the parent path does not exist, SharePoint returns an error rather than creating intermediate directories.
Method 2: Using the folders/add Method
Alternatively, you can call the add method on an existing parent folder. This method accepts the new folder name directly as an endpoint parameter:
POST https://{tenant}.sharepoint.com/sites/{site}/_api/web/GetFolderByServerRelativeUrl('/sites/Engineering/Shared Documents')/folders/add('SubfolderName')
Authorization: Bearer {token}
Accept: application/json;odata=verbose
Content-Type: application/json;odata=verbose
X-RequestDigest: {digest}
This endpoint returns HTTP 200 OK or 201 Created with the folder's OData representation. If a folder with that name already exists in that location, SharePoint REST returns HTTP 409 Conflict.
Adding Folders to Custom SharePoint Lists
Document libraries are specialized SharePoint lists configured for files. Standard SharePoint lists handle folders differently. In a standard list, a folder is an item with a specific ContentTypeId (0x0120).
Creating a folder in a custom list requires a two-step process:
Step 1: Create the item with folder content type
Post to the list items endpoint setting ContentTypeId to 0x0120:
POST https://{tenant}.sharepoint.com/sites/{site}/_api/web/lists/getByTitle('ProjectTracking')/items
Authorization: Bearer {token}
Accept: application/json;odata=verbose
Content-Type: application/json;odata=verbose
X-RequestDigest: {digest}
{
"__metadata": { "type": "SP.Data.ProjectTrackingListItem" },
"Title": "Phase-1",
"ContentTypeId": "0x0120"
}
Step 2: Update the FileLeafRef property
SharePoint creates the item but may label the folder name using the integer item ID. Issue an HTTP POST request with an X-HTTP-Method: MERGE header to assign the folder name to FileLeafRef:
POST https://{tenant}.sharepoint.com/sites/{site}/_api/web/lists/getByTitle('ProjectTracking')/items({item-id})
Authorization: Bearer {token}
Accept: application/json;odata=verbose
Content-Type: application/json;odata=verbose
X-HTTP-Method: MERGE
If-Match: *
X-RequestDigest: {digest}
{
"__metadata": { "type": "SP.Data.ProjectTrackingListItem" },
"FileLeafRef": "Phase-1"
}
Path Constraints and Naming Rules
When scripting folder creation across SharePoint, enforce these filesystem rules in your client validation:
- Forbidden characters: Folder names cannot contain
" * : < > ? / \ | # % - Reserved names: Avoid
.lock,CON,PRN,AUX,NUL,COM1throughCOM9,LPT1throughLPT9, and names beginning with_vti_. - Path length: In SharePoint Online, the complete decoded server-relative URL path cannot exceed 400 characters.
Connect SharePoint files to your agent workspaces
Sync existing SharePoint libraries into shared Fast.io workspaces where agents search indexed files over MCP instead of traversing raw APIs. Monthly plans start with a 30-day free trial.
Why Recursive SharePoint Traversal Fails Autonomous AI Agents
Enterprise teams keep vast stores of institutional documentation across SharePoint and OneDrive. As engineering groups deploy autonomous AI agents (running in Claude Code, Cursor, Codex, or custom agent frameworks) to analyze project history or generate deliverables, a common pattern is attempting to connect the agent directly to SharePoint via Graph API.
This direct approach breaks down quickly in production. Agents designed to explore directory trees and read files encounter architectural bottlenecks inherent to enterprise cloud storage.
The Token and Context Penalty of Raw API Traversal
When an agent attempts to find information by querying SharePoint APIs directly, it must perform multiple discovery queries:
- Calling
/sitesto locate the site. - Calling
/drivesto identify document libraries. - Calling
/items/{id}/childrenrepeatedly to traverse nested directories. - Paginating through results when folders exceed 200 items.
Each Graph API response returns extensive JSON metadata containing OData annotations, permission hashes, and ETags. Feeding these directory payloads into the agent's context window consumes thousands of prompt tokens before the model even reads a document. If the agent needs to inspect a 20-page specification, downloading the raw binary file and parsing it locally adds substantial latency and compute overhead.
Rate Limiting and Graph API Throttling
Microsoft Graph enforces strict service limits to protect tenant performance. Requests that exceed concurrency thresholds receive HTTP 429 Too Many Requests responses with a Retry-After header. When multiple autonomous agents run parallel research tasks or recursively scan document libraries, they trigger rate limits. Managing exponential backoff and request queues in agent code increases complexity and stalls user workflows.
Claude Cowork Connector Performance Context
The operational cost of direct storage traversal was evaluated in multi-provider testing. The connector comparison is published at Fastio benchmarks and that page is the only place its numbers live. Fastio was measured the fastest and the lowest cost of the providers tested.
Every measured row in that evaluation reflects that provider's native connector in Claude Cowork. No row is a local stdio server, a Files-On-Demand stub, or SharePoint, and SharePoint was not measured in that test. However, the architectural lesson applies directly: relying on an agent to pull full files and traverse remote cloud folders via native storage APIs is slower and more expensive than querying an intelligent workspace.
How Fast.io and MCP Bridge SharePoint to Agent Workspaces
The solution to the agent storage bottleneck is separating institutional file storage from agent coordination. Your organization keeps its primary documents in SharePoint, preserving existing compliance, access controls, and user habits. Meanwhile, relevant document libraries sync into Fast.io workspaces where agents interact through a standardized Model Context Protocol (MCP) server.
Cloud Sync Architecture
Fast.io provides Cloud Sync for Dropbox, Box, and OneDrive. SharePoint document libraries connect directly through the OneDrive connector. Sync operates one-way or two-way, on a schedule or on demand. It is never continuous, live, or real-time. (Google Drive is import today with sync coming soon).
+-----------------------------+
| SharePoint Online Library |
| (Enterprise System) |
+-----------------------------+
|
| Cloud Sync via OneDrive Connector
| (Scheduled or On Demand)
v
+-----------------------------+
| Fast.io Workspace |
| - Intelligence Mode (RAG) |
| - Full-Text + Semantic |
| - Metadata Views |
| - Advisory File Leases |
| - Append-Only Audit Log |
+-----------------------------+
|
| Streamable HTTP (/mcp/tools or /mcp/code)
v
+-----------------------------+
| Autonomous AI Agents |
| (Claude Code, Cursor, etc) |
+-----------------------------+
When files sync into a Fast.io workspace, Intelligence Mode auto-indexes every document upon arrival. Instead of downloading whole files or traversing raw folder trees, the agent executes targeted semantic searches across the workspace, receiving exact passages with document citations.
Structured Document Extraction with Metadata Views
For teams managing contracts, invoices, or technical specifications, Metadata Views transform unstructured documents into queryable tables. Users describe required fields in natural language, and the system populates typed columns (Text, Integer, Decimal, Boolean, URL, JSON, Date & Time) across PDFs, spreadsheets, and Word documents without OCR templates. Agents query these extracted schemas directly via MCP, eliminating the need to read entire documents to locate specific data points.
Remote MCP Server Endpoints
Fast.io exposes a consolidated MCP toolset hosted over Streamable HTTP. Agents connect to dedicated endpoints based on their operational profile:
- Coding Agents (Claude Code, Cursor, Gemini CLI, Devin, Cline): Connect to
https://mcp.fast.io/mcp/code. These agents use search and execute tools to manage workspace files. - General Clients & Claude Apps (Claude Desktop, web, mobile): Connect to
https://mcp.fast.io/mcp/tools. Write actions route through_managetools (storage_manage,workspace_manage), while read queries usestorage. - ChatGPT and Codex: Install the Fastio plugin from the ChatGPT plugin directory, or configure a custom MCP server at
https://mcp.fast.io/mcp/operations.
Documentation for configuring MCP connections is available at Fast.io MCP setup and the agent reference at Fast.io MCP guide. Interactive clients authenticate via OAuth in the browser without managing raw credentials. Headless scripts and background servers send an API key as an Authorization: Bearer <api key> header.
Multi-Agent Coordination and Handoff
When multiple agents work within a shared workspace, Fast.io provides mechanisms to maintain order:
- Advisory File Locks: An agent acquires a temporary lease on a file using
lock-acquireonstorage_manage, checks lock status withlock-statusonstorage, and releases it withlock-release. Locks require heartbeating to remain active. They do not prevent concurrent writes; instead, they signal intent while per-file version history preserves every version. - Events Feed: Agents subscribe to workspace activity over WebSocket or long-polling (
GET /current/activity/poll/{entity_id}) to react when new files land. - Ownership Transfer: An autonomous agent can initialize an organization, provision project workspaces, and transfer ownership to a human team member while retaining administrative access.
Transparent Pricing and Getting Started
Monthly plans start with a 30-day free trial, which requires a credit card. Fast.io provides structured tiers for teams of all sizes, with storage, seats, workspaces, and AI credits included in every plan.
Credits meter AI processing, including semantic search, document summarization, and metadata extraction, while storage and seat allocations are fixed with each plan tier.
Sources
References used to verify factual claims in this guide.
-
When creating a folder via Microsoft Graph, successful calls return a 201 Created response code and a DriveItem resource.
Frequently Asked Questions
How do I create a folder in SharePoint using REST API?
To create a folder in SharePoint using the REST API, send an HTTP POST request to https://{tenant}.sharepoint.com/sites/{site}/_api/web/folders. Include headers for Content-Type and Accept set to application/json;odata=verbose, along with an Authorization Bearer token (or an X-RequestDigest value). In the JSON body, provide __metadata with type SP.Folder and set ServerRelativeUrl to the full path of the target folder, such as /sites/Engineering/Shared Documents/NewFolder. If the folder already exists, the API returns HTTP 409 Conflict.
How do I create a folder in a SharePoint document library using Microsoft Graph?
To create a folder in a SharePoint document library using Microsoft Graph, send an HTTP POST request to https://graph.microsoft.com/v1.0/sites/{site-id}/drives/{drive-id}/root/children (or replace root with items/{parent-item-id} for subfolders). In the request body, pass a JSON object containing the folder name, an empty folder facet object ('folder': {}), and optionally @microsoft.graph.conflictBehavior set to rename, replace, or fail. The endpoint returns HTTP 201 Created with the drive item metadata.
How do AI agents automate SharePoint directory creation?
AI agents can automate SharePoint directory creation by issuing authenticated Microsoft Graph API calls or by using Fast.io workspaces connected to SharePoint through Cloud Sync. In a synced architecture, agents create folders and manage files using Fast.io MCP tools over Streamable HTTP, allowing background sync to update SharePoint while the agent queries auto-indexed files with semantic search.
What permissions are required to create folders in SharePoint via Microsoft Graph?
Creating folders in SharePoint via Microsoft Graph requires Files.ReadWrite or Files.ReadWrite.All for delegated user contexts, or Files.ReadWrite.All or Sites.ReadWrite.All for application-only daemon contexts in Microsoft Entra ID. The application registration must receive administrator consent for application-level permissions.
How does SharePoint handle naming conflicts when creating folders via API?
Microsoft Graph handles naming conflicts using the @microsoft.graph.conflictBehavior property in the request body, which accepts rename (appends an incrementing number), replace (returns the existing item), or fail (returns HTTP 409 Conflict). In contrast, the legacy SharePoint REST API does not support automatic renaming and returns HTTP 409 Conflict whenever a folder with that name already exists.
Can AI agents interact with SharePoint files without downloading entire folders?
Yes. By syncing SharePoint document libraries into a Fast.io workspace using Cloud Sync via the OneDrive connector, files are automatically indexed for hybrid search upon arrival. AI agents connect to the remote Fast.io MCP server to execute semantic queries and retrieve specific text passages and citations directly, eliminating the need to download whole multi-gigabyte folder trees.
Related Resources
Connect SharePoint files to your agent workspaces
Sync existing SharePoint libraries into shared Fast.io workspaces where agents search indexed files over MCP instead of traversing raw APIs. Monthly plans start with a 30-day free trial.