A common problem when creating sites which use the Twitter API is how to store and display user profile images.
When you query the API the resulting user data gives you the URL of the user profile image. However this image URL is not a permalink. If the user changes their profile image the image URL will change.
Twitter also seem to periodically change the image URLS, presumably as part of their content distribution network.
Cache the images
One solution is to save a copy of the image to the site locally and use it as a cache. This will ensure that the images never go missing, but if your site serves a lot of Twitter users then you could end up having to cache thousands of images which could be expensive.
It also means that if the user decides to update their image on Twitter your cached version will be out of date.
Twitter API
The Twitter API documentation leads you to believe that the only solution to this problem is either caching the images locally, as I described, or sending a new authenticated query each time you need to see the image.
This would be way too slow and quickly eat up your API query allowance.
The secret profile image url
There is another way which isn’t well publicised but is really useful.
Once you have the user’s Twitter ID or screenname, you can use the following URL format:
https://twitter.com/api/users/profile_image?id=337098150
This will redirect to the live thumbnail for that user
If you’d rather use the screenname, the URL is
https://twitter.com/api/users/profile_image/tweetedtrips
Don’t forget that a user may change their screenname, so it is less reliable as a permalink that the ID. Of course if a user deletes their account altogether you’re still going to get a missing image.
Nice, now make it bigger
This returns the 48px x 48px size of the profile image, if you’d rather use the larger 73px x 73px version then add ?size-bigger to the end of the URL:
https://twitter.com/api/users/profile_image/tweetedtrips?size=bigger
or
https://twitter.com/api/users/profile_image?id=337098150&size=bigger
The only downside to this method is that due to the redirection that must take place the images may take slightly longer to load.
Also, because this is an undocumented feature there is the risk that Twitter may change or remove this functionality at any time. But those who have used the Twitter API in the past should be quite used to this unpredictable behaviour!