If you assumed that SharePoint’s REST API would return the document icon for your document by default, you’d be wrong. If you don’t assume that, then you’re smarter than me. Come to find out there is a separate API to call to get the icon.
The REST API to get the icon is
https://[tenant].sharepoint.com/_api/web/maptoicon(filename='filename.pdf', progid='', size='0')
The size options, 1 or 0, return the image for 32×32 or 16×16, respectively. If you’re listing your documents in a list view similar to SharePoint, you’ll want to use 0.
Here’s a little snippet using it with jQuery to get your icons back:
//fileName would be any filename, like This is my file.pdf or Document.docx var url = _spPageContextInfo.webAbsoluteUrl + "/_api/web/maptoicon(filename='" + fileName + "',progid='',size=0)"; $.getJSON(url) .then((data) => { var icon = $("<img src='" + _spPageContextInfo.webAbsoluteUrl + "/_layouts/15/images/" + data.value + "'/>") //now throw your icon object into wherever you want to use it })
Til next time, Happy SharePointing!
Great article David. This really help me. Thanks
Awesome!
Hi, this api seems to be missing a lot of file types, like mp4 mp3.
Looking at the modern library, it has icons for every file I could test with. It looks like the icons are cdn hosted rather than SP
Any ideas is there is an updated API?
I believe that’s it. This is what Microsoft uses to get the icons, from what I can tell. I’m sure they’re keeping it up to date, kind of ;)