studyapi / app.py
GalvaoFilho's picture
Create app.py
3aa94c4 verified
from fastapi import FastAPI, HTTPException
from fastapi.middleware.cors import CORSMiddleware
import random
app = FastAPI(title="PokeAula API")
# Liberando CORS para que o React (localhost ou netlify/vercel) consiga acessar
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_methods=["*"],
allow_headers=["*"],
)
# Simulando um Banco de Dados de Pokémons
# Estruturado para praticar acesso a propriedades: pokemon.stats.hp
pokedex = [
{
"id": 1,
"name": "Bulbasaur",
"type": ["Gramas", "Veneno"],
"image": "https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/1.png",
"stats": {"hp": 45, "attack": 49, "defense": 49}
},
{
"id": 4,
"name": "Charmander",
"type": ["Fogo"],
"image": "https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/4.png",
"stats": {"hp": 39, "attack": 52, "defense": 43}
},
{
"id": 7,
"name": "Squirtle",
"type": ["Água"],
"image": "https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/7.png",
"stats": {"hp": 44, "attack": 48, "defense": 65}
},
{
"id": 25,
"name": "Pikachu",
"type": ["Elétrico"],
"image": "https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/25.png",
"stats": {"hp": 35, "attack": 55, "defense": 40}
}
]
@app.get("/pokemon")
def list_all():
"""Retorna todos para o primeiro fetch da aula."""
return pokedex
@app.get("/pokemon/{id}")
def get_one(id: int):
"""Para testar async/await com parâmetros e erro 404."""
pokemon = next((p for p in pokedex if p["id"] == id), None)
if not pokemon:
raise HTTPException(status_code=404, detail="Pokémon não encontrado na base de dados da aula!")
return pokemon
@app.get("/battle-check")
def battle():
"""Rota instável para praticar try/catch (erro 500 aleatório)."""
if random.random() < 0.5:
raise HTTPException(status_code=500, detail="A batalha caiu! Tente novamente.")
return {"status": "Vitória!", "xp_ganho": 150}