Introduction

SharePoint document libraries are the backbone of content collaboration in Microsoft 365. Teams use them to store, share, and co-author documents. For developers, enabling programmatic file and folder management within custom solutions is a common requirement.

With SPFx and Graph API, developers can interact with SharePoint document libraries efficiently.

Why Use Graph API for SharePoint Document Libraries?

Accessing a Document Library

To interact with a SharePoint document library, you must know the siteId and driveId.

const client = await this.context.msGraphClientFactory.getClient("3");

// Get all drives (document libraries) for a site
const drives = await client.api("/sites/{siteId}/drives").get();
console.log(drives.value);

// Get files/folders inside a document library
const files = await client
  .api(`/sites/{siteId}/drives/{driveId}/root/children`)
  .get();
console.log(files.value);

Common Operations in SharePoint Document Libraries

1. Create a Folder

This creates a new folder named “TeamReports” in the root of the selected document library.

const folder = {
  name: "TeamReports",
  folder: {},
  "@microsoft.graph.conflictBehavior": "rename",
};
await client.api(`/sites/{siteId}/drives/{driveId}/root/children`).post(folder);

2. Upload a File

This uploads a new file (update.txt) into the “TeamReports” folder.

const fileContent = new Blob(["Team update"], { type: "text/plain" });
await client
  .api(`/sites/{siteId}/drives/{driveId}/root:/TeamReports/update.txt:/content`)
  .put(fileContent);

3. Download a File

This retrieves a file’s contents from the “TeamReports” folder for further use.

const file = await client
  .api(`/sites/{siteId}/drives/{driveId}/root:/TeamReports/update.txt:/content`)
  .get();

4. Delete a File

This permanently removes a file from the SharePoint document library.

await client.api(`/sites/{siteId}/drives/{driveId}/root:/TeamReports/update.txt`).delete();

Best Practices for SharePoint File Management

  1. Permission control → Ensure users only see what they’re allowed to.

  2. Upload sessions → Handle large files efficiently.

  3. Error handling → Retry on throttling (HTTP 429).

  4. Structured naming → Keep files and folders consistent for automation.

Real-World Example

For a project site, developers can create SPFx web parts to automatically generate a folder structure (like “Design,” “Testing,” “Reports”) and upload standard templates when a new project is initiated.

Conclusion

Using the Microsoft Graph API in SPFx provides a robust way to manage SharePoint document libraries. From automating folder creation to enabling file uploads, developers can deliver collaboration features directly inside SharePoint and Teams, enhancing user productivity.