Exemplos Práticos
🌐 API Pública: JSONPlaceholder
API gratuita para testes e prototipação.
💡 Buscar Posts
// Buscar todos os posts
fetch('https://jsonplaceholder.typicode.com/posts')
.then(res => res.json())
.then(posts => {
console.log('Total de posts:', posts.length);
posts.forEach(post => {
console.log(post.title);
});
});
💡 Buscar Post Específico
// Buscar post com ID 1
fetch('https://jsonplaceholder.typicode.com/posts/1')
.then(res => res.json())
.then(post => {
console.log('Título:', post.title);
console.log('Corpo:', post.body);
});
💡 Criar Novo Post
fetch('https://jsonplaceholder.typicode.com/posts', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
title: 'Meu Post',
body: 'Conteúdo do post',
userId: 1
})
})
.then(res => res.json())
.then(post => console.log('Post criado:', post));
🌍 API: REST Countries
API para obter informações sobre países.
💡 Buscar País
fetch('https://restcountries.com/v3.1/name/brazil')
.then(res => res.json())
.then(countries => {
const brazil = countries[0];
console.log('País:', brazil.name.common);
console.log('Capital:', brazil.capital[0]);
console.log('População:', brazil.population);
});
⚛️ Usando em React
💡 Componente com useEffect
import { useState, useEffect } from 'react';
function PostsList() {
const [posts, setPosts] = useState([]);
useEffect(() => {
fetch('https://jsonplaceholder.typicode.com/posts')
.then(res => res.json())
.then(data => setPosts(data));
}, []);
return (
<div>
{posts.map(post => (
<div key={post.id}>
<h3>{post.title}</h3>
<p>{post.body}</p>
</div>
))}
</div>
);
}
Dica
Use useEffect para fazer requisições quando o componente montar. Sempre trate erros e estados de carregamento!