Comandi Bruno
Bruno è un client API lightweight, open-source e nativo Git progettato per testare e sviluppare API. A differenza di Postman, Bruno memorizza le tue collezioni come file di testo semplice (formato .bru) che possono essere versionati con Git, rendendolo ideale per la collaborazione di team e pipeline CI/CD.
Installazione
| Piattaforma | Comando |
|---|---|
| macOS (Homebrew) | brew install bruno |
| Linux (Snap) | snap install bruno |
| Linux (APT) | sudo apt-get install bruno |
| Windows (Chocolatey) | choco install bruno |
| npm | npm install -g @usebruno/cli |
| Download | Visita usebruno.com/downloads |
Introduzione
Avvia Bruno GUI
bruno
Crea una Nuova Collezione
bruno create-collection my-api-collection
Apri Collezione Esistente
bruno /path/to/collection
Gestione Collezioni
Struttura Collezione
Bruno memorizza le collezioni come directory con file .bru:
my-api-collection/
├── bruno.json # Metadati collezione
├── environments/
│ ├── Development.json
│ └── Production.json
├── auth/
│ └── auth.bru
└── users/
├── get-all-users.bru
├── create-user.bru
└── update-user.bru
Importa da Postman
# In Bruno GUI: Import → Seleziona collezione JSON Postman
# O usa CLI (se disponibile per la tua versione di Bruno)
Organizza Richieste in Cartelle
Crea cartelle all’interno della tua collezione per organizzare le richieste:
- Fai clic destro nell’albero collezione → Nuova Cartella
- Nomina le cartelle logicamente (es. users, products, auth)
- Trascina le richieste tra cartelle
Esporta Collezione
# Le collezioni sono memorizzate come file semplice (formato .bru)
# Semplicemente commit su Git o condividi la directory
Linguaggio Bru (Formato Richiesta)
Bruno utilizza file .bru—un semplice linguaggio di markup leggibile per le richieste.
File Richiesta Base
meta {
name: Get All Users
type: http
seq: 1
}
get {
url: {{baseUrl}}/api/users
auth: bearer
}
params:query {
limit: 10
offset: 0
}
headers {
Content-Type: application/json
User-Agent: Bruno/v1
}
auth:bearer {
token: {{authToken}}
}
Richiesta con Body
meta {
name: Create User
type: http
seq: 2
}
post {
url: {{baseUrl}}/api/users
}
headers {
Content-Type: application/json
}
body:json {
{
"name": "John Doe",
"email": "john@example.com",
"role": "admin"
}
}
Richiesta Form Data
meta {
name: Upload Profile Picture
type: http
seq: 3
}
post {
url: {{baseUrl}}/api/users/{{userId}}/avatar
}
body:form-urlencoded {
username: johndoe
email: john@example.com
}
Form Multipart (File Upload)
meta {
name: Upload File
type: http
seq: 4
}
post {
url: {{baseUrl}}/api/files/upload
}
body:multipartForm {
file: @/path/to/file.pdf
description: My document
}
Comandi CLI
Esegui Collezione o Richiesta
# Esegui l'intera collezione
bru run /path/to/collection
# Esegui richiesta specifica
bru run /path/to/collection/requests/get-users.bru
# Esegui con ambiente specifico
bru run /path/to/collection --env Production
# Esegui in formato reporter json
bru run /path/to/collection --reporter json
# Esegui con report HTML
bru run /path/to/collection --reporter html --output report.html
Reporter Disponibili
| Reporter | Comando |
|---|---|
| CLI (default) | bru run collection --reporter cli |
| JSON | bru run collection --reporter json |
| HTML | bru run collection --reporter html --output report.html |
| JUnit | bru run collection --reporter junit |
Esegui con Variabili
# Passa variabili di ambiente
bru run /path/to/collection --env Development
# Sovrascrivi variabile specifica
bru run /path/to/collection --env Production --variable apiKey=abc123
Fail on Error
# Esci con stato non-zero se qualsiasi test fallisce (utile per CI/CD)
bru run /path/to/collection --failOnError
Output Verboso
# Mostra informazioni dettagliate di richiesta/risposta
bru run /path/to/collection --verbose
Variabili di Ambiente
Crea File Ambiente
I file ambiente sono memorizzati come environments/EnvName.json:
{
"baseUrl": "https://api.example.com",
"apiKey": "your-api-key-here",
"authToken": "bearer-token",
"userId": "12345",
"timeout": 5000
}
Usa Variabili nelle Richieste
get {
url: {{baseUrl}}/api/users/{{userId}}
timeout: {{timeout}}
}
headers {
Authorization: Bearer {{authToken}}
X-API-Key: {{apiKey}}
}
Cambia Ambienti
# Via CLI
bru run /path/to/collection --env Development
# Via GUI: Seleziona ambiente dal dropdown in Bruno interface
Tipi Variabili Ambiente
| Tipo | Esempio | Utilizzo |
|---|---|---|
| String | "apiKey": "abc123" | {{apiKey}} |
| Number | "timeout": 5000 | {{timeout}} |
| Boolean | "debug": true | {{debug}} |
| Object | "config": {...} | Accedi con scripting |
Gestione Segreti
# Crea file .env per dati sensibili (aggiungi a .gitignore)
echo "PROD_API_KEY=secret123" > .env
# Usa nel file ambiente con riferimento
# O usa Bruno GUI per marcare campi come "Secret"
Script Pre-Richiesta
Aggiungi JavaScript prima che la richiesta sia inviata:
// Imposta valori dinamici
bru.setEnvVar('timestamp', Date.now());
bru.setEnvVar('nonce', Math.random().toString(36).substring(7));
// Logica condizionale
if (bru.getEnvVar('env') === 'production') {
bru.setEnvVar('timeout', 10000);
}
// Log info debug
console.log('Sending request to', bru.getEnvVar('baseUrl'));
Script Post-Risposta
Esegui JavaScript dopo aver ricevuto la risposta:
// Accedi dati risposta
const responseData = res.getBody();
const statusCode = res.getStatus();
const headers = res.getHeaders();
// Salva valori per prossima richiesta
if (statusCode === 200) {
bru.setEnvVar('authToken', responseData.token);
bru.setEnvVar('userId', responseData.user.id);
}
// Log risposta
console.log('Status:', statusCode);
console.log('Response:', JSON.stringify(responseData, null, 2));
Operazioni Risposta Comuni
// Ottieni status code
const status = res.getStatus();
// Ottieni body come string
const body = res.getBody();
// Parse JSON body
const data = res.getBody(true); // true = parse as JSON
// Ottieni headers
const contentType = res.getHeader('content-type');
// Ottieni header specifico
const authHeader = res.getHeader('authorization');
Assertions e Test
Built-in Test Assertions
// Status code assertion
tests['Status is 200'] = (res.getStatus() === 200);
// Response body contains
tests['Response contains user'] = res.getBody().includes('john');
// JSON response validation
const data = res.getBody(true);
tests['User ID exists'] = data.user && data.user.id > 0;
// Response time
tests['Response time < 500ms'] = res.getResponseTime() < 500;
// Header validation
tests['Content-Type is JSON'] = res.getHeader('content-type').includes('application/json');
Esempio Test Complesso
const data = res.getBody(true);
tests['Status is 201'] = res.getStatus() === 201;
tests['ID is a number'] = typeof data.id === 'number';
tests['Email is valid'] = /^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$/.test(data.email);
tests['Created at is ISO date'] = !isNaN(Date.parse(data.createdAt));
// Salva per prossima richiesta
if (tests['Status is 201']) {
bru.setEnvVar('newUserId', data.id);
}
Autenticazione
Bearer Token
auth:bearer {
token: {{authToken}}
}
Basic Auth
auth:basic {
username: {{username}}
password: {{password}}
}
API Key (Header)
headers {
X-API-Key: {{apiKey}}
Authorization: ApiKey {{apiKey}}
}
API Key (Query Parameter)
params:query {
api_key: {{apiKey}}
apiToken: {{token}}
}
OAuth 2.0
auth:oauth2 {
grant_type: authorization_code
authorization_url: https://provider.com/oauth/authorize
token_url: https://provider.com/oauth/token
client_id: {{clientId}}
client_secret: {{clientSecret}}
scope: read write
}
Digest Auth
auth:digest {
username: {{username}}
password: {{password}}
}
Tipi Richieste e Metodi
GET Request
meta {
name: Fetch User
type: http
seq: 1
}
get {
url: {{baseUrl}}/api/users/{{userId}}
}
params:query {
includeProfile: true
fields: id,name,email
}
POST Request
post {
url: {{baseUrl}}/api/users
}
body:json {
{
"name": "Jane Doe",
"email": "jane@example.com"
}
}
PUT/PATCH Request
put {
url: {{baseUrl}}/api/users/{{userId}}
}
body:json {
{
"name": "Jane Smith",
"status": "active"
}
}
DELETE Request
delete {
url: {{baseUrl}}/api/users/{{userId}}
}
Richiesta con Headers
headers {
Content-Type: application/json
Accept: application/json
User-Agent: Bruno/v1.0
X-Request-ID: {{requestId}}
Authorization: Bearer {{token}}
}
Funzionalità Avanzate
Variabili a Livello Collezione
Definisci variabili in bruno.json:
{
"name": "My API Collection",
"version": "1.0",
"variables": {
"baseUrl": "https://api.example.com",
"version": "v1",
"defaultTimeout": 5000
}
}
Sequenziamento Richieste
Controlla l’ordine di esecuzione richieste nel CLI runner:
meta {
name: Authenticate
type: http
seq: 1
}
meta {
name: Get User Data
type: http
seq: 2
}
Le richieste vengono eseguite in ordine seq.
GraphQL Queries
meta {
name: GraphQL Query
type: http
seq: 1
}
post {
url: {{baseUrl}}/graphql
}
body:graphql {
query {
user(id: "{{userId}}") {
id
name
email
}
}
}
Query Parameters
params:query {
page: 1
limit: 10
sort: -createdAt
filter: status:active
}
Git Workflow
Perché Git-Native Importa
# Collezioni memorizzate come file di testo
.bru/
├── users/
│ ├── get-user.bru
│ └── create-user.bru
└── products/
└── list-products.bru
# Facile da version control
git add .
git commit -m "Update API requests"
git push origin main
# Merge conflicts sono gestibili
# Rivedi cambiamenti in PRs
# Collabora con team
Workflow Collaborativo
# Team member clona collezione
git clone https://github.com/team/api-collection.git
cd api-collection
# Installa Bruno CLI
npm install -g @usebruno/cli
# Esegui test localmente
bru run . --env Development
# Fai cambiamenti
# Aggiungi nuove richieste o aggiorna quelle esistenti
# Commit e push
git add .
git commit -m "Add payment API endpoints"
git push origin feature/payments
Ignora File Sensibili
# .gitignore nella radice collezione
.env
.env.local
environments/Production.json
!environments/Production.json.example
secrets/
node_modules/
Integrazione CI/CD
GitHub Actions
name: API Tests
on: [push, pull_request]
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: Install Node.js
uses: actions/setup-node@v3
with:
node-version: '18'
- name: Install Bruno CLI
run: npm install -g @usebruno/cli
- name: Run API tests
run: bru run . --env CI --reporter json --output test-results.json
- name: Upload results
if: always()
uses: actions/upload-artifact@v3
with:
name: test-results
path: test-results.json
GitLab CI
api-tests:
image: node:18
script:
- npm install -g @usebruno/cli
- bru run . --env CI --reporter json --output test-results.json
artifacts:
paths:
- test-results.json
reports:
junit: test-results.json
Local Pre-commit Hook
#!/bin/bash
# .git/hooks/pre-commit
echo "Running API tests..."
bru run . --env Development --failOnError
if [ $? -ne 0 ]; then
echo "API tests failed. Commit aborted."
exit 1
fi
Workflow Comuni
Test REST API
# 1. Imposta ambiente
bru run /path/to/collection --env Development
# 2. Controlla risultati test
# Test pass/fail visualizzati in output
# 3. Genera report
bru run /path/to/collection --env Development --reporter html --output report.html
Load Testing con Richieste Parallele
// In script pre-richiesta
for (let i = 0; i < 10; i++) {
bru.setEnvVar('iteration', i);
}
Generazione Dati Dinamici
// Genera email univoca per richiesta
const timestamp = Date.now();
bru.setEnvVar('dynamicEmail', `user_${timestamp}@example.com`);
// Genera ID casuale
bru.setEnvVar('randomId', Math.floor(Math.random() * 10000));
Chaining Richieste
// In script post-risposta della prima richiesta
const data = res.getBody(true);
bru.setEnvVar('userId', data.id);
// La prossima richiesta usa {{userId}}
Debug
Abilita Modalità Verbose
bru run /path/to/collection --verbose
Visualizza Dettagli Richiesta/Risposta
In Bruno GUI:
- Clicca richiesta
- Visualizza tab “Params” per query params
- Visualizza tab “Body” per request body
- Visualizza tab “Response” per response data
- Visualizza tab “Tests” per risultati test
Console Logging
// In script pre-richiesta o post-risposta
console.log('Variable value:', bru.getEnvVar('baseUrl'));
console.log('Full response:', res.getBody());
console.log('Status code:', res.getStatus());
Network Inspection
// Controlla response headers
const headers = res.getHeaders();
console.log('All headers:', headers);
// Controlla response time
console.log('Response time:', res.getResponseTime(), 'ms');
Best Practices Struttura File
api-collection/
├── README.md # Documentazione
├── .gitignore # Ignora file sensibili
├── bruno.json # Metadati collezione
├── environments/ # File ambiente
│ ├── Development.json
│ ├── Staging.json
│ └── Production.json
├── globals.json # Variabili globali
├── auth/
│ ├── login.bru
│ └── refresh-token.bru
├── users/
│ ├── get-all-users.bru
│ ├── get-user-by-id.bru
│ ├── create-user.bru
│ ├── update-user.bru
│ └── delete-user.bru
├── products/
│ ├── list-products.bru
│ └── get-product.bru
└── scripts/
├── test-runner.js
└── helpers.js
Risorse
| Risorsa | URL |
|---|---|
| Official Website | usebruno.com |
| GitHub Repository | github.com/usebruno/bruno |
| Documentation | docs.usebruno.com |
| Download | usebruno.com/downloads |
| Discord Community | discord.gg/usebruno |
| Bru Language Spec | github.com/usebruno/bru |
| API Testing Guide | docs.usebruno.com/api-testing |
| GitHub Issues | github.com/usebruno/bruno/issues |
Suggerimenti e Trucchi
- Git Diff per Reviews: Poiché le collezioni sono file, usa
git diffper rivedere i cambiamenti API prima del merge - Environment Templates: Crea file
.example.jsonper ambienti per condividere la struttura di configurazione senza segreti - Reusable Scripts: Memorizza script di test comuni in file
.jsseparati e referenzia - Variable Scope: Le variabili di collezione si applicano globalmente; le variabili a livello di richiesta le sovrascrrivono
- Performance: Usa flag
--failOnErrorin CI/CD per catturare fallimenti test presto - Documentation: Aggiungi commenti nei file
.bruusando sintassi// comment - Versioning: Includi versione API nell’URL di base per facile cambio tra versioni