2021年4月11日星期日

How to make a Google Translate API V3 simple HTTP POST request?

I am aware that documentation exists... It's just so damn cryptic and convoluted, typical overengineering. It has to be simpler.

I don't want to use 3rd party libraries... I want a beautiful vanilla js fetch.

I am trying the following with nodejs...

let url = `https://translation.googleapis.com/v3/projects/PROJECT_ID:translateText?key=API_KEY`;    let response = await fetch(url, {      method: "POST",      withCredentials: true,      credentials: "include",      headers: {          Authorization: "bearer",                   "Content-Type": "application/json",      },      body: {          sourceLanguageCode: "en",          targetLanguageCode: "ru",          contents: ["Dr. Watson, come here!"],          mimeType: "text/plain",      },  });    let result = await response.json();    console.log(result);  

And getting this error:

{ error:     { code: 401,       message:        'Request is missing required authentication credential. Expected OAuth 2 access token, login cookie or other valid authentication credential. See https://developers.google.com/identity/sign-in/web/devconsole-project.',       status: 'UNAUTHENTICATED' }   }  

Does anyone know the right concoction to pull this off?

Here's a V2 working request:

let url = `https://translation.googleapis.com/language/translate/v2?key=${API_KEY}&format=text&source=de&target=en&q=${encodeURIComponent(query)}`;  
https://stackoverflow.com/questions/67050536/how-to-make-a-google-translate-api-v3-simple-http-post-request April 12, 2021 at 05:53AM

没有评论:

发表评论