I want to fetch data from google analytics via google data api. The request is given below.
export async function fetchAnalyticsData() {
// getAccessToken();
const GA4_PROPERTY_ID = "";
const url = `https://analyticsdata.googleapis.com/v1beta/properties/${GA4_PROPERTY_ID}:runReport`;
const requestOptions = {
method: "POST",
headers: {
"Content-Type": "application/json",
// Add your authorization token here if required
Authorization: "Bearer YOUR_ACCESS_TOKEN",
},
body: JSON.stringify({
dateRanges: [{ startDate: "2023-09-01", endDate: "2023-09-15" }],
dimensions: [{ name: "country" }],
metrics: [{ name: "activeUsers" }],
}),
};
try {
const response = await fetch(url, requestOptions);
const data = await response.json();
console.log(data); // Do whatever you need with the data
} catch (error) {
console.error("Error fetching data:", error);
}
}
This request gives 401. "Request had invalid authentication credentials. Expected OAuth 2 access token, login cookie or other valid authentication credential".
So, I created Oauth2 client id and client secret:
(https://i.stack.imgur.com/iDSSU.png)
How can i take a token for the request by using client id and secret if possible. I do not want users to login. -
This is my sample for accessing the real-time API you're going to have to change it to work with the standard reports
config.js
realtime.js
This should be enough to get you started until I have time to create another sample for the standard reports