How websites fetch data from APIs (explained with a simple Pokémon project)
When I first started learning JavaScript, I didn’t really understand how websites actually get their data. I thought everything was just written into the page somewhere.
Then I built a small project where I generated a random Pokémon, and that was the first time I worked with an API.
So instead of explaining this in a complicated way, I’ll just use that project as an example.
What is an API?
An API is basically a place where you can ask for data.
Instead of storing everything yourself, you can send a request to another server and it gives you the data back.
In my case, I used the Pokémon API. It has data for all Pokémon, like their names, images, stats and more. I didn’t create any of that data myself. I just asked for it.
What happens when you click the button
In my project, there is just a button. When you click it, a few things happen in the background.
First, a random number is generated. This number represents a Pokémon.
Then a URL is created that looks something like this:
https://pokeapi.co/api/v2/pokemon/25
That request is sent to the API. The API then responds with data about that Pokémon.
How the code actually fetches the data
This is the important part. In JavaScript, you can use fetch() to request data from an API.
My code looks like this:
let id = Math.floor(Math.random() * 1024) + 1;
let fetchid = "https://pokeapi.co/api/v2/pokemon/" + id;
fetch(fetchid)
.then(response => response.json())
.then(data => {
imgElement.src = data.sprites.front_default;
output.innerHTML = data.name;
});
What this does is:
It sends a request to the API, waits for a response, and then converts that response into usable data. After that, it takes the name and the image and puts them into the website.
Why this matters
This is basically how a lot of modern websites work.
Instead of loading everything at once, they request data when they need it. That’s how you get things like dynamic content, live updates, or personalized information.
Even though my project is very small, the idea behind it is the same.
Why I used Pokémon
I think this part is important. If you build something like this, it should be fun.
Pokémon was just an easy choice because it’s familiar and there’s a public API for it. It made the whole thing more interesting to build and easier to understand.
Final thoughts
This was one of the first projects where I understood that websites are not just static pages. They can request data, process it, and show something new every time.
And once you understand this, a lot of things in web development start to make more sense.
Comments
Post a Comment