Fetching the Preview URL of a SharePoint Document with REST API
Problem: Imagine you want to display a preview of a document from a SharePoint Document Library directly within your application. While SharePoint offers an intuitive preview feature, accessing it through the REST API can seem tricky.
Solution: This article guides you through the process of retrieving the preview URL of a document in a SharePoint Document Library using the REST API.
Scenario: You're building a web application that showcases documents from a SharePoint Document Library. You want to display a preview of the document before users click to open the full file.
Original Code (JavaScript):
// Replace with your SharePoint site URL and document library name
const siteUrl = "https://yourtenant.sharepoint.com/sites/yoursite";
const libraryName = "Documents";
const documentId = "1234567890abcdef"; // Replace with your document ID
// Construct the REST API endpoint
const requestUrl = `${siteUrl}/_api/web/GetFileByServerRelativeUrl('/sites/yoursite/Documents/YourDocument.pdf')/listItemAllFields`;
// Make the REST API request
fetch(requestUrl, {
method: "GET",
headers: {
"Accept": "application/json;odata=verbose",
"Authorization": `Bearer ${accessToken}` // Replace with your valid access token
}
})
.then(response => response.json())
.then(data => {
// Extract the preview URL from the response
const previewUrl = data.d.FileRef.replace("Documents", "Forms/DispForm.aspx?ID=") + data.d.ID;
console.log("Preview URL:", previewUrl);
// Use the previewUrl to display the document preview in your application
})
.catch(error => console.error("Error fetching preview URL:", error));
Explanation:
- Endpoint Construction: The
requestUrl
is constructed to retrieve the list item's AllFields properties using the_api/web/GetFileByServerRelativeUrl
endpoint. This provides us with the necessary metadata for constructing the preview URL. - Authorization: Replace the placeholder
accessToken
with a valid OAuth access token granted by your SharePoint application. This ensures your request is authenticated. - Data Extraction: After the successful API call, the response's
FileRef
property contains the relative URL of the document and theID
property holds the list item ID. - Preview URL Formation: The preview URL is constructed by replacing "Documents" in the
FileRef
with "Forms/DispForm.aspx?ID=" and appending theID
value.
Key Points & Considerations:
- Authentication: Always ensure your REST API requests are authenticated with a valid access token. You can obtain this token using various authentication methods like OAuth2.
- File Type Support: Preview URLs are only available for file types that SharePoint natively supports for previewing.
- Customizations: SharePoint allows customization of preview behaviors. If your library has specific settings, the preview URL generation might differ.
Further Enhancements:
- Error Handling: Implement comprehensive error handling to catch potential issues and gracefully handle them.
- Dynamic Document Selection: Make the code dynamic by fetching the document ID and name from user input or a data source.
- UI Integration: Incorporate the generated preview URL into your application's UI using an
<iframe>
or a dedicated preview component.
Conclusion: By utilizing the REST API and understanding the relevant properties within the response, you can effectively retrieve the preview URL of a SharePoint document and enhance your application's user experience by providing quick visual previews. Remember to always prioritize security, implement robust error handling, and tailor the code to your application's specific requirements.