JavaScript: an AI API
Send a question to Gemini with fetch and read the answer from the object. The key stays secret.
All lessons · JavaScript lessons: learn from scratch
The API and the key
You do not write the model from scratch. An API is the bridge between your code and a ready model. The code sends a question and the server returns an answer. For a start, Gemini gives a free key and does not ask for a card. On aistudio.google.com choose Get API key, then Create API key. The key is like a password: do not share it and do not put it on a public GitHub.
The request is an object
The question travels inside an object. The answer text is at candidates[0].content.parts[0].text. candidates is an array, so you write [0]. If you forget [0], the result is undefined.
const sorguMelumati = {
contents: [
{
parts: [{ text: "JavaScript-də dəyişən nədir?" }]
}
]
};Send it with fetch
POST sends the question. JSON.stringify turns the object into text so it can travel. cavab.json() turns the answer back into an object. The key must not have a space at the start or the end. Do not put the key inside the page: anyone who sees it can take it.
const apiKey = "BURAYA_OZ_API_ACARINIZI_YAZIN";
const url = `https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash:generateContent?key=${apiKey}`;
fetch(url, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(sorguMelumati)
})
.then(cavab => cavab.json())
.then(melumat => {
const aiMetni = melumat.candidates[0].content.parts[0].text;
console.log(aiMetni);
});Questions
Why do you get 400 or 403? The key is wrong, or there is a space around it. Inside the quotes there should be only the key.
Why does the body not go? You cannot write the object directly. You need JSON.stringify(sorguMelumati).
Why is the answer undefined? candidates is an array. You must write [0]. candidates.content is wrong.
Where do you read the text? melumat.candidates[0].content.parts[0].text