SDKs
SDK TypeScript/JavaScript
Carregando conteúdo...
Nesta página
SDK oficial da brapi para TypeScript e JavaScript. Roda em Node.js e no navegador, com tipos para parâmetros e respostas, retry e erros por status HTTP. O SDK é gerado a partir do OpenAPI.
npm install brapi
# ou
yarn add brapi
# ou
pnpm add brapi
# ou
bun add brapiGuarde sua chave em um arquivo .env:
BRAPI_API_KEY=sua_chaveimport Brapi from 'brapi';
const client = new Brapi({
apiKey: process.env.BRAPI_API_KEY,
});
const quote: Brapi.QuoteRetrieveResponse = await client.quote.retrieve('PETR4');
console.log(quote.results[0].regularMarketPrice);
// Vários tickers em uma chamada
const quotes = await client.quote.retrieve('PETR4,VALE3,ITUB4');Não use a chave em código que roda no navegador. Chame a brapi do seu backend.
const client = new Brapi({
apiKey: process.env.BRAPI_API_KEY, // obrigatório
environment: 'production', // 'production' ou 'sandbox'
maxRetries: 2, // padrão: 2
timeout: 60000, // em ms, padrão: 60000
});Crie um cliente e use o mesmo em todo o app.
const quote = await client.quote.retrieve('PETR4');
const quoteWithModules = await client.quote.retrieve('PETR4', {
modules: 'summaryProfile,balanceSheetHistory',
});
console.log(quote.results[0]);
// {
// symbol: 'PETR4',
// shortName: 'PETROBRAS PN',
// regularMarketPrice: 38.45,
// regularMarketChangePercent: 2.15,
// currency: 'BRL',
// ...
// }const stocks = await client.quote.list({
page: 1,
limit: 50,
});
console.log(stocks.stocks);
// [
// { stock: 'PETR4', name: 'Petrobras PN', type: 'stock' },
// ...
// ]const crypto = await client.crypto.retrieve('BTC');
const cryptos = await client.crypto.available();
const currency = await client.currency.retrieve('USD-BRL');
const currencies = await client.currency.available();
const inflation = await client.inflation.retrieve('IPCA');
const inflationCountries = await client.inflation.available();
const selic = await client.primeRate.retrieve('SELIC');
const primeRateCountries = await client.primeRate.available();inflation e primeRate chamam endpoints descontinuados. Use os dados de
macroeconomia. Veja Versionamento.
try {
const quote = await client.quote.retrieve('INVALID');
} catch (error) {
if (error instanceof Brapi.APIError) {
console.log(error.status); // 404
console.log(error.name); // 'NotFoundError'
console.log(error.message);
console.log(error.headers);
}
}| Status | Erro | Causa |
|---|---|---|
| 400 | BadRequestError | Requisição inválida. |
| 401 | AuthenticationError | Chave ausente ou inválida. |
| 403 | PermissionDeniedError | O plano não inclui o recurso. |
| 404 | NotFoundError | Recurso não encontrado. |
| 422 | UnprocessableEntityError | Parâmetros inválidos. |
| 429 | RateLimitError | Cota ou limite de requisições simultâneas. |
| >=500 | InternalServerError | Erro no servidor. |
| N/A | APIConnectionError | Falha de conexão. |
O SDK repete a requisição 2 vezes por padrão em erros de conexão, 408, 409, 429 e 5xx.
const client = new Brapi({
apiKey: process.env.BRAPI_API_KEY,
maxRetries: 0, // desliga o retry
timeout: 10000, // 10 segundos para todas as requisições
});
// Timeout de uma requisição
const quote = await client.quote.retrieve('PETR4', {
timeout: 5000,
});// app/stock/[ticker]/page.tsx
import Brapi from 'brapi';
const client = new Brapi({
apiKey: process.env.BRAPI_API_KEY,
});
export default async function StockPage({
params,
}: {
params: { ticker: string };
}) {
const quote = await client.quote.retrieve(params.ticker);
const stock = quote.results[0];
return (
<div>
<h1>{stock.shortName}</h1>
<p>R$ {stock.regularMarketPrice.toFixed(2)}</p>
</div>
);
}import express from 'express';
import Brapi from 'brapi';
const app = express();
const client = new Brapi({
apiKey: process.env.BRAPI_API_KEY,
});
app.get('/api/quote/:ticker', async (req, res) => {
try {
const quote = await client.quote.retrieve(req.params.ticker);
res.json(quote);
} catch (error) {
if (error instanceof Brapi.NotFoundError) {
res.status(404).json({ error: 'Ticker not found' });
} else {
res.status(500).json({ error: 'Internal server error' });
}
}
});
app.listen(3000);import type {
QuoteRetrieveResponse,
QuoteListResponse,
CryptoRetrieveResponse,
CurrencyRetrieveResponse,
InflationRetrieveResponse,
} from 'brapi';