Simple Javascript Code Sample Demonstrating the Use of Google OAuth 2.0 and the Google Photos REST API
3 min readAug 3, 2022
--
Set up a new Google Project
- Start a new project on Google Cloud Console
- Enable the Photos Library API
- Go to APIs and Services → Credentials
- Click Create Credentials and select OAuth Client ID
- Select web application and fill in the fields like this:
6. Note the client id and client secret which are used in the code.
Start a local web server on default port 8000
Python -m SimpleHTTPServer
Javascript Code
Copy and paste the following code into index.html and place it in the same directory as the web server is running under.
<div style="display: table;clear: both;"><div style="font-family:georgia; width:50%; float:left;" id=albums>
</div><div style="font-family:georgia; width:50%; float:left;" id=photos>
</div></div><script>// access tokenvar access;var albums = [];
var photos = [];function getCodeOrToken()
{
var queryString = window.location.search;
var urlParams = new URLSearchParams(queryString);
var code = urlParams.get("code");if (code == null)
{
// if the page is called without a code then request a code
// replace the client id with yoursvar url =
"https://accounts.google.com/o/oauth2/auth?access_type=offline&client_id=829835459694-67ormfm9b5qttqtbrkt9aonfgmf8l73j.apps.googleusercontent.com&redirect_uri=http://localhost:8000&response_type=code&scope=https://www.googleapis.com/auth/photoslibrary.readonly%20https://www.googleapis.com/auth/photoslibrary.appendonly";window.location.href = url;
}
else
{
// if the page is called with a code then request a tokengetToken(code);
}
}function getToken(code)
{
// request an access tokenvar ajax2 = new XMLHttpRequest();var url = "https://oauth2.googleapis.com/token";
ajax2.open("POST", url, true);
ajax2.setRequestHeader('Content-Type', 'application/json');ajax2.send(JSON.stringify({
code: code,// *** use your client idclient_id: "829835459694-67ormfm9b5qttqtbrkt9aonfgmf8l73j.apps.googleusercontent.com",// replace client secret with yourclient_secret: "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
redirect_uri: encodeURI("http://localhost:8000"),
grant_type: "authorization_code"}));ajax2.onload = function()
{
var r = JSON.parse(ajax2.responseText);
access = r.access_token;
getList(null);
};
}function getList(pageToken)
{
// get all of the user's albumsvar ajax1 = new XMLHttpRequest();var url = "https://photoslibrary.googleapis.com/v1/albums?pageSize=50";
if (pageToken != null) url += "&pageToken=" + pageToken;ajax1.open("GET", url, true);
ajax1.setRequestHeader('Content-Type', 'application/json');
ajax1.setRequestHeader('Authorization', "Bearer " + access);ajax1.send(null);ajax1.onload = function()
{
var r = JSON.parse(ajax1.responseText);if (r.albums == null) return;for (var i = 0; i < r.albums.length; ++i)
{
var a = {id: r.albums[i].id, title: r.albums[i].title, count: r.albums[i].mediaItemsCount};
albums.push(a);
}if (r.nextPageToken != null)
{
// if nextPageToken is not null go back for moregetList(r.nextPageToken);
}
else
{
// if nextPageToken is null display the albumsdisplayAlbums();
}
};
}function displayAlbums()
{
for (var i = 0; i < albums.length; ++i)
{
var s =
" <div style='cursor: pointer;' onclick='getAlbum(\"" + albums[i].id + "\", null);'>" +
albums[i].title +
"</div> " +
//albums[i].count +
"<br>";
document.getElementById("albums").innerHTML += s;
}
}function getAlbum(id, pageToken)
{
// when an album is clicked get all the photos in that albumvar ajax1 = new XMLHttpRequest();var url = "https://photoslibrary.googleapis.com/v1/mediaItems:search";if (pageToken == null)
photos = []
else
url += "?pageToken=" + pageToken;ajax1.open("POST", url, true);
ajax1.setRequestHeader('Content-Type', 'application/json');
ajax1.setRequestHeader('Authorization', "Bearer " + access);ajax1.send(JSON.stringify({
"albumId": id}));ajax1.onload = function()
{
var r = JSON.parse(ajax1.responseText);if (r.mediaItems == null) return;console.log("photos " + r.mediaItems.length);for (var i = 0; i < r.mediaItems.length; ++i)
{
var a = {id: r.mediaItems[i].baseUrl, name: r.mediaItems[i].filename};
photos.push(a);
}if (r.nextPageToken != null)
{
// if nextPageToken is not null go back for moregetAlbum(id, r.nextPageToken);
}
else
{
// if nextPageToken is null display the photosdisplayPhotos();
}
};
}function displayPhotos()
{
document.getElementById("photos").innerHTML = "";for (var i = 0; i < photos.length; ++i)
{
var s = "<img height=200 src=" + photos[i].id + ">";
document.getElementById("photos").innerHTML += s + " ";
}
}// start the processgetCodeOrToken();</script>