Взаимодействие с API
Получайте данные из интернета с помощью искусственного интеллекта.
«Взаимодействие с API» — бесплатный урок Vibe Coding на CoddyKit. Это урок 1 из 4. Ты можешь прочитать весь урок бесплатно ниже — а потом практиковать его прямо в браузере с встроенным редактором кода и ИИ-репетитором 24/7. Это часть пути обучения Vibe Coding, и твой прогресс синхронизируется между веб-версией и приложением CoddyKit. Курс Vibe Coding содержит 4 уроков всего.
Части этого урока еще не переведены и отображаются на английском.
Apps Talk to Other Apps
Real apps rarely live alone. A weather app asks a weather service for data. A crypto tracker asks a price service. The way apps ask each other for data is called an API — an Application Programming Interface.
Think of an API like a waiter: you don't go into the kitchen, you just ask for what you want and the waiter brings it back. As a vibe coder, you mostly describe what data you need, and AI writes the code that talks to the API for you.
What 'Fetching Data' Means
When your app gets data from the internet, we say it fetches it. The app sends a request to a URL, and the service sends back data — usually as JSON, a simple text format that looks like labeled boxes of values.
You don't need to memorize how this works. You just need to know the words so you can tell AI: 'fetch the data and show it on the page.'
{
"city": "Tokyo",
"temperature": 21,
"condition": "Sunny"
}Your First API Prompt
Let's ask AI to fetch real data. The trick is to name the data you want and where to show it. Here is a prompt you could paste into Cursor, Claude Code, Bolt or v0.
Notice how the prompt names a specific free API and exactly what to display. Specific prompts get working code on the first try.
Create a single HTML page that fetches a random
activity from the Bored API
(https://www.boredapi.com/api/activity) when the
page loads, and displays the activity text in a
big centered card. Add a "Give me another" button
that fetches a new one. Use plain JavaScript, no
frameworks.What fetch() Looks Like
When AI writes the code, you'll often see a fetch() call. You don't have to write it by hand, but recognizing it helps you read what AI gives you.
This tiny example fetches a fake user and logs their name. Run it to see data come back from the internet.
fetch('https://jsonplaceholder.typicode.com/users/1')
.then(response => response.json())
.then(user => {
console.log('Name:', user.name);
console.log('Email:', user.email);
});Reading JSON Responses
API data comes back as JSON. To use a value, you reach into it by name with a dot, like user.name. Nested data uses more dots: user.address.city.
When you're unsure what's inside a response, ask AI: 'log the full response so I can see its shape, then show me how to read the fields I need.'
const user = {
name: 'Ada',
address: { city: 'London' }
};
console.log(user.name);
console.log(user.address.city);Handling Slow or Failed Requests
The internet isn't always reliable. A request can be slow, or the service can be down. Good apps show a loading message while waiting and a friendly error message if something breaks.
Always remind AI to handle these. A prompt like the one below produces a much more robust app than just 'fetch the data.'
Add a loading spinner while the data is being
fetched, and if the request fails, show a friendly
message like "Couldn't load data, try again" with
a retry button. Don't let the app crash on errors.Free APIs to Practice With
You can build a lot with free, no-signup APIs. Great ones for learning:
- JSONPlaceholder — fake users, posts and todos
- Open-Meteo — real weather, no key needed
- REST Countries — country info and flags
- The Cat / Dog API — random pet pictures
Tell AI which one to use and what to display, and you have a working app in minutes.
Build a country explorer page using the REST
Countries API (https://restcountries.com/v3.1/all).
Show each country's flag, name, and population in a
grid of cards. Add a search box that filters
countries by name as I type.API Keys: Why Some APIs Need One
Some services need to know who is asking, so they give you an API key — a secret password for your app. You include it with each request.
Keys keep services from being abused, but they must be kept secret. For now, just know that 'this API needs a key' means an extra setup step. We cover keeping keys safe in a later lesson.
Asking AI to Wire Up an API
When you have an API's documentation, you can hand it to AI directly. Paste the example URL and a sample response, and let AI map it to your screen.
This is one of the biggest vibe-coding superpowers: you don't read the docs deeply, you let AI translate them into working code.
Here is an example API response from the weather
service:
{"current":{"temperature_2m":18.4,"wind_speed_10m":7}}
Fetch from
https://api.open-meteo.com/v1/forecast?latitude=52.5&longitude=13.4¤t=temperature_2m,wind_speed_10m
and display the temperature and wind speed in two
labeled boxes on the page.Combining Multiple APIs
Powerful apps mix data from several sources. A travel app might combine a country API for facts, a weather API for the forecast, and an image API for photos.
You can ask AI to combine them step by step. Build one API first, confirm it works, then say 'now also add the weather for that country.' Small steps keep the AI accurate.
Now extend the country page: when I click a
country card, fetch that country's current weather
from Open-Meteo using its capital coordinates and
show it in a popup. Keep the existing search
feature working.You Don't Need to Memorize APIs
There are thousands of APIs, and you'll never memorize them. The vibe-coding skill is knowing the vocabulary — fetch, request, response, JSON, key — so you can describe what you want clearly.
Whenever you hit a new API, paste its docs to AI and say what data you need and where to show it. That single habit unlocks almost any data source on the web.
Quick Check
An API sends data back to your app, usually in a simple text format with labeled values. What is that format most commonly called?
Recap: Talking to APIs
You learned that apps fetch data from other services through APIs, usually getting back JSON. You saw fetch() in action, how to read response fields with dots, and why apps need loading and error states.
Most importantly: you don't memorize APIs — you describe the data you want and let AI wire it up, pasting docs and example responses when needed. Next, you'll have AI read and save files for your apps.
Изучай JavaScript с ИИ-репетитором — бесплатно
Пиши и запускай код прямо в браузере, получай мгновенную помощь от ИИ-репетитора 24/7 и продолжи учиться на сайте или в приложении.
- Курсы
- 25
- Уроки
- 100
Часто задаваемые вопросы
Урок «Взаимодействие с API» бесплатный?
Да — полный текст урока «Взаимодействие с API» бесплатно доступен здесь в веб-версии. Чтобы практиковать его интерактивно (встроенный редактор кода и ИИ-репетитор 24/7) и разблокировать остальной курс Vibe Coding, подпишись на CoddyKit PRO. Курс Vibe Coding содержит 4 уроков всего.
Чему я научусь в уроке «Взаимодействие с API»?
Получайте данные из интернета с помощью искусственного интеллекта. Ты практикуешь Vibe Coding с помощью реального кода, который запускаешь прямо в браузере, и ИИ-репетитор 24/7 отвечает на твои вопросы во время урока.
Нужен ли мне опыт, чтобы начать Vibe Coding?
Предыдущий опыт не требуется. Vibe Coding на CoddyKit структурирован для всех уровней — от новичков до продвинутых, поэтому ты можешь начать отсюда или с самого начала и учиться в своем темпе. Это урок 1 из 4.
Сколько времени занимает урок «Взаимодействие с API»?
Большинство уроков CoddyKit занимают около 5–10 минут. Каждый из них компактный и интерактивный, поэтому ты постоянно делаешь прогресс и продолжаешь с того же места в веб-версии и приложении.
Можно ли писать и запускать код в этом уроке Vibe Coding?
Да. Каждый урок Vibe Coding включает встроенный редактор кода, поэтому ты пишешь и запускаешь реальный код прямо в браузере и получаешь моментальную обратную связь от AI — локальная установка не требуется.
Все уроки этого курса
- Взаимодействие с API
- Чтение и сохранение файлов
- Простое хранение данных
- Работа с секретами и ключами