File size: 2,176 Bytes
3aa94c4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
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}