DEV Community

Cover image for How to Integrate an AI API into a Web Application: A Beginner's Guide.
Skillyards
Skillyards

Posted on

How to Integrate an AI API into a Web Application: A Beginner's Guide.

The first time a website you built answers a question on its own, it feels a little like magic. A few minutes later, the doubts start. Where does the key go? What does this cost? Why did the page freeze?

This guide answers those questions in plain language. You do not need machine learning knowledge or a computer science degree. If you can build a basic web page and have written a little JavaScript or Python, you can add an AI feature to a real project this week.

What "Integrating an AI API" Actually Means

An AI API is a service run by a company such as Anthropic, OpenAI, or Google. Your app sends text to their servers over the internet, and their model sends text back. Your job is to send the right text, handle the reply, and show it nicely.

Three parts are involved:

  1. The browser, where the user types something.
  2. Your server, which holds your secret key and talks to the AI provider.
  3. The AI provider, which runs the model and returns an answer.

The most common beginner mistake is skipping the middle part. We will come back to it, because it is the one mistake that can cost you real money.

Five Things a Beginner Can Realistically Build

Start with a small feature that solves one problem. These five work well for a first project, and each one is useful in a portfolio.

  • A text summarizer: the user pastes a long article or notes and gets five short points back.
  • A question helper trained on your own content: You paste your FAQ or course details into the prompt, and the assistant answers only from that.
  • A content tagger: It reads a blog post or product description and suggests categories and keywords.
  • A draft writer: It turns a few form fields into a polite email or a product description.
  • A feedback explainer: A student submits a short answer and receives simple suggestions to improve it.

None of these needs a database or a complicated design. Each one is one input box, one server route, and one result area.

Step 1: Pick One Provider and Stick With It for Now

All the big providers offer official libraries for JavaScript and Python, and the basic flow is nearly identical. The best provider for you is the one you finish a project with.

  • Claude (Anthropic): The Claude API quickstart walks you through your first call to the Messages API.
  • OpenAI: Its quickstart uses the Responses API, with an official SDK for server-side JavaScript such as Node.js.
  • Gemini (Google): New accounts start on a free tier that gives access to certain models in the Gemini API and Google AI Studio, up to each model's free rate limits. That makes it a comfortable place to practice without paying anything.

One caution about free tiers. Google states that content sent on the free tier is used to improve its products and that paid-tier content is not. So while you practice, use made-up sample text. Never paste real student records, phone numbers, or client data into a free tier.

Model names change often, so always copy the current name from the provider's own documentation instead of from an old tutorial.

Step 2: Get Your API Key and Test It Without Code

Create an account on the provider's console and generate an API key. Treat it like a bank PIN. Anyone who has it can spend your money.

Before writing any code, try your idea in the provider's browser playground, such as Google AI Studio or the Anthropic Console. Type your instruction and a sample input, and see whether the answer is good enough. Ten minutes here can save you two hours of debugging later, because you will find out early whether your idea works at all.

Step 3: Keep the Key on the Server

This is the step that separates a safe project from a risky one.

If you put your key in frontend code, anyone can find it. If your API key appears anywhere in your HTML, JavaScript, or browser network requests, it is public, and anyone can view the source or open DevTools to take it. Putting it in a .env file does not fix this when you use frontend frameworks. Environment variables in frameworks like React or Vue are compiled into the client side code at build time, so they are not secret.

The fix is simple. Your browser calls your own server route, and your server calls the AI provider. The key never leaves the server.

If you use Next.js, which many Skillyards learners do, a route handler is the natural home for this code.

// app/api/summarise/route.js
import Anthropic from "@anthropic-ai/sdk";

// The library reads ANTHROPIC_API_KEY from your server environment.
const client = new Anthropic();

export async function POST(request) {
const { text } = await request.json();

// Basic checks before spending any money
if (!text || text.length > 8000) {
return Response.json(
{ error: "Please send between 1 and 8000 characters." },
{ status: 400 }
);
}

try {
const message = await client.messages. create({
model: "claude-sonnet-5-5", // copy the current name from the docs
max_tokens: 400,
system: "You summarize text for students in five short points. Use simple English."
messages: [{ role: "user", content: text }],
});

return Response.json({ summary: message.content[0].text });
Enter fullscreen mode Exit fullscreen mode

} catch (error) {
return Response.json(
{ error: "The summary service is busy. Please try again." },
{ status: 502 }
);
}
}

Store the key in a file called .env.local on your machine, add that file to .gitignore, and set the same variable in your hosting dashboard when you deploy. If you ever commit a key to GitHub by accident, delete it from your account and create a new one straight away. Removing the file is not enough, because the key stays in your Git history.

Step 4: Connect the Frontend

Your page only needs to talk to your own route:

async function summarise(text) {
const res = await fetch("/api/summarise", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ text }),
});

const data = await res.json();
if (!res.ok) throw new Error(data.error);
return data.summary;
}

Show a loading message while you wait, because AI calls can take a few seconds. Show a friendly message if something fails. Disable the button while a request is running so nobody clicks it ten times.

Step 5: Make the Answer Feel Fast With Streaming

By default, the user stares at a blank space until the whole answer is ready. Streaming sends the answer in small pieces, so words appear as they are written, like a chat.

You do not have to build this from scratch. The Vercel AI SDK has a Next.js quickstart where a route handler uses streamText, and a useChat hook in the @ai-sdk/react package handles the chat interface for you. Build the simple version first, then add streaming once it works.

Step 6: Write a Good Instruction (The System Prompt)

The quality of your feature depends mostly on the instruction you give the model. A useful instruction has four parts:

Who it is: "You are a helpful assistant for a computer education institute."
What it should do: "Answer questions about course duration and syllabus."
What it must not do: "If the answer is not in the information below, say you do not know and suggest contacting the team."
How it should sound: "Use short sentences and simple English."

The third part matters most. AI models can sound confident and still be wrong. For anything involving fees, dates, or admission rules, give the model your verified information inside the prompt and tell it to use only that. Then test it with questions you know the answers to.

Step 7: Control Your Costs Before They Control You

Providers charge by tokens, which are small pieces of text, roughly parts of words. You pay for what you send and for what comes back. A few habits keep the bill small:

Set max_tokens so one answer cannot run on forever.
Limit the input length, as the example above does.
Use a smaller, cheaper model for simple jobs like tagging or summarizing.
Add a per-user limit on your server so one person cannot send a thousand requests.
Save repeated answers. If fifty visitors ask the same question, you can reuse one answer.
Check the spending controls in your provider's console and set a limit if one is offered.

Free tiers are good for learning but have strict limits. For Gemini, rate limits are applied per project, not per API key, so creating extra keys will not give you extra room. Prices and limits change often, so read the provider's current pricing page, such as the Gemini pricing page, before you decide anything.

Six Mistakes Beginners Make

Calling the AI directly from the browser. This exposes your key.
Trusting every answer. Always read outputs, especially for facts and numbers.
Skipping error handling. APIs sometimes fail or slow down, and your page should cope calmly.
Sending private data. Keep personal details out of prompts unless you understand the provider's data policy.
Building a huge app first. One working feature beats five half-finished ones.
Following old tutorials. Model names and SDK details move quickly, so use official documentation.
A Realistic Plan for Your First Weekend

Saturday morning: Pick one idea from the list above. Test it in a playground with five sample inputs.

Saturday afternoon: Create the server route, store your key safely, and get one successful response in your terminal.

Sunday morning: Build the input box and result area. Add loading and error messages.

Sunday afternoon: Improve your instruction using ten test inputs. Add a length limit and a simple request limit. Deploy it and put the link in your portfolio.

At the end, you will have something many beginners lack: a live project that uses a real AI service, with a safe setup you can explain in an interview.

Where This Skill Takes You

Adding an AI API is one of the fastest ways to make a project feel current, and it builds the habits employers look for: working with APIs, protecting secrets, handling errors, and thinking about cost. If you are still choosing a stack, our guides on MERN vs MEAN and React vs Next.js vs Vue will help. To understand how your server routes should be designed, read API Design Basics: REST vs. GraphQL and Authentication, Authorization, and Security Basics.

If you want to build projects like this alongside a recognised degree, the On-Job Degree Programmer at Skillyards combines DBRAU-affiliated BCA studies with full stack training, paid internships and placement support, right here in Agra. You can also explore the BCA programme page for details.

Frequently Asked Questions

  • Do I need to know machine learning to use an AI API?
    No. You send text and receive text. The model is already built, and your work is regular web development.

  • Is there a free way to start?
    Yes. Google AI Studio offers a free tier with limits, and other providers may offer trial credits that change from time to time. Check each provider's current page.

  • Which language should I use?
    JavaScript or Python. Both have official libraries from the major providers.

  • Can I call the AI API directly from React?
    Not safely with a private key. Route the call through your own server.

  • How much will it cost?
    For a small practice project, usually very little, because you pay per token. Set output limits and spending controls from day one.

  • Which provider is best for beginners?
    Any of the three major ones works. Choose one, finish a project and then try another.

Top comments (1)

Collapse
 
mohsen_jr profile image
Mohsen jr •

The per-user rate limit is important, but what happens when someone bypasses it by creating multiple accounts? I’d combine it with an IP-based limit and a global spending cap to avoid unexpected API costs.