> ## Documentation Index
> Fetch the complete documentation index at: https://docs.ghosting.fun/llms.txt
> Use this file to discover all available pages before exploring further.

# Exemplos de código: integre a API Ghosting em minutos

> Snippets prontos para consultar a API pública Ghosting em cURL, JavaScript, TypeScript, Node.js com Axios e Python. Copie, cole e adapte para seu projeto.

Esta página reúne exemplos completos de integração com o endpoint `GET /api/v1/users/:username` em várias linguagens. Todos os exemplos incluem tratamento de erro básico e podem ser colados diretamente em seus projetos.

## cURL

```bash Terminal theme={null}
# Consulta direta via rota REST
curl -X GET "https://ghosting.fun/api/v1/users/ghosting" \
  -H "Accept: application/json"

# Consulta alternativa via query parameter
curl -X GET "https://ghosting.fun/api/v1/users?username=ghosting" \
  -H "Accept: application/json"
```

## JavaScript / TypeScript (Fetch API)

```typescript ghosting.ts theme={null}
interface GhostingProfile {
  username: string;
  displayName: string;
  avatarUrl: string;
  pageUrl: string;
  views: number;
  status: "active" | "suspended";
  banInfo: {
    isBanned: boolean;
    reason: string | null;
  };
  badges: {
    isVerified: boolean;
    isOfficial: boolean;
    isHelper: boolean;
  };
}

async function getGhostingProfile(username: string): Promise<GhostingProfile> {
  const cleanUsername = username.trim().replace(/^@/, "");
  const response = await fetch(`https://ghosting.fun/api/v1/users/${cleanUsername}`);

  if (!response.ok) {
    if (response.status === 404) {
      throw new Error(`Perfil @${cleanUsername} não encontrado no Ghosting.`);
    }
    throw new Error(`Erro na API Ghosting: HTTP ${response.status}`);
  }

  const json = await response.json();
  return json.data;
}

// Exemplo de uso
getGhostingProfile("ghosting")
  .then((profile) => {
    console.log(`Nome: ${profile.displayName} (@${profile.username})`);
    console.log(`Views: ${profile.views} | Status: ${profile.status}`);
  })
  .catch((err) => console.error(err.message));
```

## Node.js (Axios)

```javascript ghosting.js theme={null}
const axios = require("axios");

async function fetchUser(username) {
  try {
    const { data } = await axios.get(`https://ghosting.fun/api/v1/users/${username}`);
    if (data.success) {
      console.log("Perfil:", data.data.displayName);
      console.log("Avatar:", data.data.avatarUrl);
    }
  } catch (error) {
    if (error.response && error.response.status === 404) {
      console.log("Usuário não existe.");
    } else {
      console.error("Erro na requisição:", error.message);
    }
  }
}

fetchUser("ghosting");
```

## Python (requests)

```python ghosting.py theme={null}
import requests

def get_ghosting_profile(username: str):
    clean_username = username.strip().lstrip("@")
    url = f"https://ghosting.fun/api/v1/users/{clean_username}"

    response = requests.get(url, headers={"Accept": "application/json"})

    if response.status_code == 200:
        body = response.json()
        user = body.get("data")

        print(f"Nome: {user['displayName']} (@{user['username']})")
        print(f"Bio: {user['bio']}")
        print(f"Views: {user['views']}")
        print(f"Verificado: {user['badges']['isVerified']}")

        if user["status"] == "suspended":
            print(f"Atenção: Perfil suspenso! Motivo: {user['banInfo']['reason']}")

        return user

    elif response.status_code == 404:
        print(f"Perfil @{clean_username} não encontrado.")
        return None
    else:
        print(f"Erro na requisição: {response.status_code}")
        return None

profile = get_ghosting_profile("ghosting")
```

<Tip>
  Sempre normalize o username removendo espaços e o caractere `@` antes de enviar à API. O endpoint não aceita o `@` no path.
</Tip>

## Próximos passos

<CardGroup cols={2}>
  <Card title="Bot Discord" icon="chat" href="/guias/bot-discord">
    Slash command completo para Discord.js v14.
  </Card>

  <Card title="Arquitetura de moderação" icon="shield" href="/guias/moderacao">
    Como tratar perfis suspensos que retornam HTTP 200.
  </Card>
</CardGroup>
