Getting started overview
Getting started with OneDrive for development primarily involves leveraging the Microsoft Graph API, which provides a unified endpoint for accessing data across Microsoft 365 services, including OneDrive. This integration allows developers to manage files, folders, and other data programmatically. The initial setup requires a Microsoft account, app registration within the Azure portal, and understanding the OAuth 2.0 authorization flow to obtain access tokens for authenticated requests.
The process outlined below focuses on setting up a development environment to interact with OneDrive using its API. This includes steps for account creation, application registration, and making a basic API call to verify connectivity. Developers can choose between various SDKs—including those for iOS, Android, Universal Windows Platform, JavaScript, and .NET—or interact directly with the REST API. The Microsoft Graph documentation serves as the authoritative source for detailed API references and authorization flows.
This guide will walk through the essential steps to get an application integrated with OneDrive, covering both personal and business accounts where applicable through the Microsoft Graph permissions model. While OneDrive offers a free tier with 5 GB of storage, more extensive usage or business features typically require a Microsoft 365 subscription.
| Step | What to Do | Where |
|---|---|---|
| 1. Create Account | Sign up for a Microsoft account (personal or work/school) | Microsoft account sign-up page |
| 2. Register Application | Register your application in Azure AD to get Client ID/Secret | Azure portal App registrations |
| 3. Grant Permissions | Configure API permissions for Microsoft Graph (e.g., Files.ReadWrite) |
Azure portal App registrations > API permissions |
| 4. Obtain Token | Implement OAuth 2.0 flow to acquire an access token | Microsoft Graph authentication documentation |
| 5. Make First Request | Use the access token to call a OneDrive API endpoint | Graph Explorer or custom application |
Create an account and get keys
To begin using OneDrive capabilities programmatically, you first need a Microsoft account. This can be a personal account (e.g., Outlook.com, Live.com) or a work/school account provided by an organization using Microsoft 365. If you do not have one, you can create a new Microsoft account.
Microsoft Account Setup
- Personal Account: Go to the OneDrive homepage and select "Sign up for free" to create a new Outlook.com email and associated Microsoft account. This grants you 5 GB of free OneDrive storage.
- Work/School Account: If you are part of an organization that uses Microsoft 365, your administrator will typically provide you with an account. Access to OneDrive for Business is managed through your organization's Microsoft 365 subscription.
Application Registration in Azure AD
API access to OneDrive is managed through Microsoft Graph, which requires your application to be registered in the Azure Active Directory (Azure AD) portal. This process generates the necessary credentials for your application to authenticate with Microsoft services.
- Access Azure Portal: Navigate to the Azure portal. Sign in with your Microsoft account (the same one you plan to use for development).
- App registrations: In the Azure portal, search for and select "App registrations."
- New registration: Click on "New registration."
- Name your application: Provide a descriptive name for your application (e.g., "My OneDrive App").
- Supported account types: Choose who can use your application. For personal OneDrive integration, select "Accounts in any organizational directory (Any Azure AD directory - Multitenant) and personal Microsoft accounts (e.g. Skype, Xbox)." For business-specific applications, you might select a more restrictive option.
- Redirect URI: Specify the redirect URI. This is where the authentication response will be sent after a user grants consent. For web applications, this might be
https://localhost:3000or your application's domain. For mobile or desktop apps, usehttps://login.microsoftonline.com/common/oauth2/nativeclientor a custom URI scheme. - Register: Click "Register."
Obtain Client ID and Secret
After registration, you will be redirected to your application's overview page.
- Client ID (Application ID): On the overview page, note down the "Application (client) ID." This is a unique identifier for your application.
- Client Secret (for confidential clients): For web applications or services that can securely store a secret, navigate to "Certificates & secrets" under "Manage." Click "New client secret," provide a description, set an expiration, and click "Add." Immediately copy the generated secret value, as it will only be shown once.
- API Permissions: Go to "API permissions" under "Manage." Click "Add a permission," select "Microsoft Graph," and then choose the delegated or application permissions your app requires. For basic file access,
Files.Read,Files.ReadWrite,Files.Read.All, orFiles.ReadWrite.Allare common. For user-specific files in their OneDrive,Files.ReadWriteis usually sufficient. Remember to grant admin consent if required for application permissions.
These credentials (Client ID and, optionally, Client Secret) are crucial for authenticating your application and obtaining access tokens.
Your first request
After setting up your account and registering your application, the next step is to make an authenticated request to the OneDrive API via Microsoft Graph. This typically involves an OAuth 2.0 flow to obtain an access token, which is then used in the Authorization header of your API calls. For simplicity, we'll demonstrate a common approach using the Microsoft Graph Explorer, a tool that allows you to experiment with Graph API calls without writing code. You can also implement this in your preferred language using an SDK or direct HTTP requests.
Using Microsoft Graph Explorer (Recommended for testing)
- Navigate to Graph Explorer: Open Graph Explorer in your web browser.
- Sign in: Click the "Sign in to Graph Explorer" button and sign in with the Microsoft account associated with your registered application and OneDrive.
- Consent to permissions: Graph Explorer might prompt you to consent to certain permissions. Ensure you grant the necessary permissions for file access (e.g.,
Files.ReadWrite.All). You can also manually add permissions under the "Modify permissions" tab in Graph Explorer. - Make a request: In the request box, select
GETas the HTTP method. - Construct the URL: To list the root contents of your OneDrive, use the URL:
https://graph.microsoft.com/v1.0/me/drive/root/children - Run Query: Click the "Run query" button.
- View Response: The "Response Preview" window will display a JSON object containing details about the files and folders in your OneDrive root directory, such as their names, IDs, and sizes.
This successful response confirms that your account is correctly set up and your application (via Graph Explorer) can access your OneDrive data.
Example: Uploading a file using cURL (Direct API approach)
To perform operations like uploading files, you will need a valid access token obtained through an OAuth 2.0 flow. For development, you can use the OAuth 2.0 authorization framework. Here's a conceptual example using cURL after you've obtained an access token (YOUR_ACCESS_TOKEN) and want to upload a small text file named hello.txt with content "Hello, OneDrive!".
curl -X PUT "https://graph.microsoft.com/v1.0/me/drive/root:/hello.txt:/content" \
-H "Authorization: Bearer YOUR_ACCESS_TOKEN" \
-H "Content-Type: text/plain" \
--data-binary "Hello, OneDrive!"
This command attempts to create or update a file named hello.txt in the root of your OneDrive with the specified content. A successful response will return a JSON object with the file's metadata, including its ID and properties.
Common next steps
Once you've successfully made your first API call, you can explore more advanced OneDrive capabilities through Microsoft Graph. Here are some common next steps for developers:
- Explore Microsoft Graph Documentation: Dive deeper into the OneDrive API documentation on Microsoft Graph to understand the full range of available endpoints for managing files, folders, sharing, and versioning.
- Integrate SDKs: For specific platforms, consider using the official SDKs (e.g., Microsoft Graph SDKs) to simplify API interactions, handle authentication, and manage data serialization/deserialization. SDKs are available for languages like C#, Python, JavaScript, Java, and Objective-C/Swift.
- Implement OAuth 2.0 Flow: For production applications, you'll need to implement a robust OAuth 2.0 authentication flow (e.g., Authorization Code Flow) to securely acquire and refresh access tokens on behalf of users. The Microsoft Graph authentication documentation provides detailed guidance.
- Handle Webhooks: Set up webhooks to receive notifications when changes occur in a user's OneDrive (e.g., file creation, modification, deletion). This enables real-time synchronization and event-driven workflows. Refer to the Microsoft Graph webhooks documentation for implementation details.
- Manage Permissions and Sharing: Learn how to manage file permissions and create sharing links programmatically. This is crucial for collaborative applications.
- Error Handling and Retries: Implement comprehensive error handling, including retries for transient errors, to make your application resilient to network issues or API rate limits.
- Security Best Practices: Adhere to security best practices for storing client secrets, handling access tokens, and validating user input to protect sensitive data. The Azure AD developer security best practices provide a good starting point.
Troubleshooting the first call
When making your initial API calls to OneDrive via Microsoft Graph, you might encounter issues. Here are common problems and their solutions:
-
Authentication Errors (401 Unauthorized):
- Missing or Expired Token: Ensure your
Authorization: Bearer YOUR_ACCESS_TOKENheader is present and the token has not expired. Access tokens typically have a short lifespan (e.g., 1 hour) and must be refreshed. - Invalid Token: The token might be malformed or issued for the wrong audience/resource. Verify your OAuth 2.0 implementation and ensure you're requesting a token for
https://graph.microsoft.com. - Incorrect Scopes: Your access token might not have the necessary permissions (scopes) granted. Double-check the "API permissions" section of your app registration in the Azure portal and ensure the user consented to these scopes. For instance, to list files, you need at least
Files.ReadorFiles.Read.All.
- Missing or Expired Token: Ensure your
-
Permission Errors (403 Forbidden):
- Insufficient Permissions: Even with a valid token, if the token's scopes do not cover the requested operation, you will get a 403. Example: trying to write a file with only
Files.Readpermission. Go back to your Azure app registration and add the required permissions (e.g.,Files.ReadWriteorFiles.ReadWrite.All) and re-authenticate to get a new token with updated scopes. - Admin Consent Required: Some permissions (especially application permissions or highly privileged delegated permissions) require an administrator to grant consent for your organization. If you are not an admin, you might need to request an administrator to grant consent via the Azure portal.
- Resource Not Found/Access Denied by User: The user whose token you are using might not have access to the specific OneDrive resource you are trying to access.
- Insufficient Permissions: Even with a valid token, if the token's scopes do not cover the requested operation, you will get a 403. Example: trying to write a file with only
-
Resource Not Found (404 Not Found):
- Incorrect URL Path: Double-check the API endpoint URL for typos or incorrect resource IDs. For example,
/me/drive/root/childrenis correct for the root folder, but a specific file requires its ID or path. - Item Does Not Exist: The file or folder you are trying to access might have been deleted or never existed at the specified path.
- Incorrect URL Path: Double-check the API endpoint URL for typos or incorrect resource IDs. For example,
-
Bad Request (400 Bad Request):
- Missing or Invalid Request Body/Headers: Ensure your request body is correctly formatted (e.g., valid JSON for POST/PATCH requests) and all required headers are present and correct (e.g.,
Content-Typefor uploads). - Invalid Parameters: Check for incorrect query parameters or values in your API call.
- Missing or Invalid Request Body/Headers: Ensure your request body is correctly formatted (e.g., valid JSON for POST/PATCH requests) and all required headers are present and correct (e.g.,
-
Rate Limiting (429 Too Many Requests):
- If you make too many requests in a short period, Microsoft Graph might temporarily block you. Implement retry logic with exponential backoff to handle these cases gracefully. The Microsoft Graph throttling guidance provides details.
For detailed error codes and troubleshooting, refer to the Microsoft Graph error codes documentation.