> For the complete documentation index, see [llms.txt](https://favelaware.gitbook.io/favelaware/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://favelaware.gitbook.io/favelaware/9-api/9.8-exemplo-pratico.md).

# 9.8 - Exemplo Prático

Vamos criar um exemplo de API simples 😮

## ⚙️ Exemplo Prático: API com Node.js + Express

### 📦 1. Inicialize o projeto.

Abra a pasta de Documentos do Windows, abra o terminal e digite:

```bash
mkdir Projects
cd Projects
mkdir simple-api
cd simple-api
```

Quando estiver no diretório `C:\Users\SeuNomeDeUsuário\Documents\Projects\simple-api`  escreva o seguinte comando:&#x20;

```bash
npm init -y
```

Após a  iniciação do Node.js for concluída,  execute o seguinte comando para instalar o Express:

```bash
npm install express
```

### 📝 2. Crie o arquivo `index.js`

{% code title="index.js" overflow="wrap" %}

```javascript
const express = require('express');
const app = express();

app.use(express.json()); // para aceitar JSON no corpo das requisições

// Dados simulados (em memória)
let users = [
  { id: 1, name: 'Gabbu' },
  { id: 2, name: 'Lia' }
];

// 📥 GET - Buscar todos os usuários
app.get('/users', (req, res) => {
  res.status(200).json(users);
});

// ➕ POST - Criar novo usuário
app.post('/users', (req, res) => {
  const { name } = req.body;
  const newUser = {
    id: users.length + 1,
    name
  };
  users.push(newUser);
  res.status(201).json(newUser);
});

// 🗑️ DELETE - Deletar usuário por ID
app.delete('/users/:id', (req, res) => {
  const userId = parseInt(req.params.id);
  users = users.filter(user => user.id !== userId);
  res.status(204).send();
});

// 🚀 Inicia o servidor
const PORT = 3000;
app.listen(PORT, () => {
  console.log(`API rodando em http://localhost:${PORT}`);
});

```

{% endcode %}

{% hint style="warning" %}
Note que não estamos usando nenhuma estrutura de projeto, colocamos toda a lógica em somente um arquivo!  \
Desafio: Montar essa mesma API no padrão estudado anteriormente.  ☝️🤓
{% endhint %}

### ▶️ 3. Execute a API.

{% code title="bash" %}

```bash
> node index.js
```

{% endcode %}

## 🧪 Testando no Postman

### 🔍 GET `/users`

* Método: `GET`
* URL: `http://localhost:3000/users`
* Retorna todos os usuários.

### ➕ POST `/users`

* Método: `POST`
* URL: `http://localhost:3000/users`
* Body (JSON):

{% code title="" overflow="wrap" fullWidth="false" %}

```json
{
  "name": "Novo Usuário"
}

```

{% endcode %}

👆 Cria um novo usuário.

### ❌ DELETE `/users/:id`

* Método: `DELETE`
* URL: `http://localhost:3000/users/1`
* Remove o usuário com `id = 1`.


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://favelaware.gitbook.io/favelaware/9-api/9.8-exemplo-pratico.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
