Używamy cookies, żeby zwiększyć Twoje doświadczenia na stronie
CodeWorlds
Powrót do kolekcji
Przewodnik20 min czytania

Insomnia - Kompletny Przewodnik po Desktop API Client

Insomnia to profesjonalny desktop API client od Kong. REST, GraphQL, gRPC testing z API design (OpenAPI), automated testing, environment variables i pluginami. Lżejsza alternatywa dla Postmana.

Insomnia - Kompletny Przewodnik po Desktop API Client

Czym jest Insomnia?

Insomnia to elegancki, wydajny i funkcjonalny desktop API client stworzony przez Kong - firmę znaną z Kong Gateway, najpopularniejszego API Gateway na świecie. W przeciwieństwie do ciężkiego Postmana, Insomnia stawia na prostotę użytkowania przy zachowaniu wszystkich profesjonalnych funkcji potrzebnych deweloperom.

Insomnia oferuje kompleksowe środowisko do pracy z API: testowanie REST, GraphQL i gRPC, projektowanie API z OpenAPI/Swagger, automatyczne testy, zarządzanie środowiskami i pluginy rozszerzające funkcjonalność. Wszystko to w aplikacji, która startuje w ułamku sekundy i nie obciąża systemu.

Stworzony w 2015 roku przez Gregory'ego Schlinkerta, Insomnia szybko zdobył popularność wśród deweloperów ceniących czystą estetykę i szybkość działania. W 2019 roku projekt został przejęty przez Kong, co przyniosło stabilne finansowanie i integrację z ekosystemem Kong. Dziś Insomnia ma miliony użytkowników i jest jednym z najpopularniejszych narzędzi do pracy z API.

Historia i filozofia projektu

Insomnia powstała z frustracji autora wobec istniejących narzędzi API. Gregory Schlinker chciał stworzyć aplikację, która:

  • Startuje natychmiast (nie jak Postman wymagający kilku sekund)
  • Ma czysty, minimalistyczny interface
  • Skupia się na tym co najważniejsze - testowaniu API
  • Nie wymusza zakładania konta do podstawowych funkcji

Ta filozofia "developer-first" przyciągnęła społeczność, która ceniła prostotę i wydajność. Po przejęciu przez Kong w 2019 roku, Insomnia zyskała wsparcie enterprise, zachowując przy tym swój minimalistyczny charakter.

Dlaczego Insomnia?

Kluczowe zalety

  1. Błyskawiczny start - Aplikacja uruchamia się w ułamku sekundy
  2. Niski zużycie zasobów - Około 150-200MB RAM vs 500MB+ dla Postmana
  3. Native OpenAPI support - Projektuj API wizualnie, generuj requesty automatycznie
  4. Request chaining - Automatycznie przekazuj dane między requestami
  5. Plugin system - Rozszerzaj funkcjonalność własnymi pluginami
  6. Git Sync - Synchronizuj projekty przez Git (nie wymaga własnego cloudu)
  7. Scratch Pad - Tryb offline bez konta, pełna prywatność
  8. Czysty design - Minimalistyczny interface bez rozpraszaczy

Insomnia vs Postman vs Hoppscotch

CechaInsomniaPostmanHoppscotch
PlatformaDesktopDesktop + WebWeb
Rozmiar~200MB~500MB~0 (web)
Start time<1s3-5sInstant
RAM usage~150MB~500MBPrzeglądarka
REST
GraphQL
gRPC
WebSocket
OpenAPI Design✅ NativePluginImport
Git Sync✅ Built-inExternalExport
Plugins
Free tier✅ Scratch PadOgraniczony✅ Full
Open SourceCzęściowoNie
Offline mode✅ (Scratch Pad)Ograniczony✅ (PWA)

Instalacja

macOS

Code
Bash
# Homebrew (zalecane)
brew install --cask insomnia

# Lub pobierz z insomnia.rest

Windows

Code
Bash
# Winget
winget install Insomnia.Insomnia

# Chocolatey
choco install insomnia-rest-api-client

# Lub pobierz instalator z insomnia.rest

Linux

Code
Bash
# Ubuntu/Debian
# Dodaj repozytorium
echo "deb [trusted=yes arch=amd64] https://download.konghq.com/insomnia-ubuntu/ default all" \
  | sudo tee /etc/apt/sources.list.d/insomnia.list

# Zainstaluj
sudo apt update && sudo apt install insomnia

# Snap
sudo snap install insomnia

# Fedora
sudo dnf install insomnia

# Arch Linux (AUR)
yay -S insomnia-bin

Konfiguracja początkowa

Code
Bash
# Po instalacji możesz:

# 1. Używać Scratch Pad (offline, bez konta)
# Pełna funkcjonalność, dane lokalne

# 2. Zalogować się (cloud sync)
# Synchronizacja między urządzeniami

# 3. Połączyć z Git (self-hosted sync)
# Kontrola wersji i współpraca przez Git

REST API Testing

Podstawowy GET request

Code
TEXT
Method: GET
URL: https://api.example.com/users

Headers:
  Accept: application/json
  Authorization: Bearer {{ _.authToken }}

# Response (200 OK)
{
  "users": [
    {"id": 1, "name": "Jan", "email": "jan@example.com"},
    {"id": 2, "name": "Anna", "email": "anna@example.com"}
  ],
  "total": 2,
  "page": 1
}

POST request z body

Code
TEXT
Method: POST
URL: {{ _.baseUrl }}/users

Headers:
  Content-Type: application/json
  Authorization: Bearer {{ _.authToken }}

Body (JSON):
{
  "firstName": "Piotr",
  "lastName": "Nowak",
  "email": "piotr@example.com",
  "role": "developer",
  "department": "Engineering"
}

# Response (201 Created)
{
  "id": "user_abc123",
  "firstName": "Piotr",
  "lastName": "Nowak",
  "email": "piotr@example.com",
  "role": "developer",
  "department": "Engineering",
  "createdAt": "2025-01-25T10:30:00Z"
}

PUT/PATCH request

Code
TEXT
Method: PATCH
URL: {{ _.baseUrl }}/users/{{ _.userId }}

Headers:
  Content-Type: application/json
  Authorization: Bearer {{ _.authToken }}

Body:
{
  "role": "senior-developer",
  "department": "Platform Engineering"
}

# Response (200 OK)
{
  "id": "user_abc123",
  "firstName": "Piotr",
  "lastName": "Nowak",
  "role": "senior-developer",
  "department": "Platform Engineering",
  "updatedAt": "2025-01-25T11:00:00Z"
}

DELETE request

Code
TEXT
Method: DELETE
URL: {{ _.baseUrl }}/users/{{ _.userId }}

Headers:
  Authorization: Bearer {{ _.authToken }}

# Response (204 No Content)

Query Parameters

Code
TEXT
Method: GET
URL: {{ _.baseUrl }}/products

Query:
  category: electronics
  minPrice: 100
  maxPrice: 1000
  inStock: true
  sort: price
  order: asc
  page: 1
  limit: 20

# Insomnia automatycznie buduje URL:
# https://api.example.com/products?category=electronics&minPrice=100&maxPrice=1000&inStock=true&sort=price&order=asc&page=1&limit=20

Różne typy Body

Code
TEXT
# 1. JSON (application/json)
{
  "name": "Product",
  "price": 99.99
}

# 2. Form URL Encoded (application/x-www-form-urlencoded)
name=Product&price=99.99

# 3. Multipart Form Data (multipart/form-data)
--boundary
Content-Disposition: form-data; name="file"; filename="image.png"
Content-Type: image/png

[binary data]
--boundary
Content-Disposition: form-data; name="description"

Product image
--boundary--

# 4. XML (application/xml)
<?xml version="1.0"?>
<product>
  <name>Product</name>
  <price>99.99</price>
</product>

# 5. Plain Text (text/plain)
Raw text content

# 6. Binary (dla file upload)
[File selector]

Environment Variables

Tworzenie środowisk

Code
JSON
// Base Environment (wspólne dla wszystkich)
{
  "apiVersion": "v1",
  "timeout": 30000,
  "retries": 3
}
Code
JSON
// Development Environment
{
  "baseUrl": "http://localhost:3000/api",
  "authToken": "dev-token-12345",
  "debugMode": true,
  "database": "dev_db",
  "logLevel": "debug"
}
Code
JSON
// Staging Environment
{
  "baseUrl": "https://staging-api.example.com",
  "authToken": "staging-token-67890",
  "debugMode": true,
  "database": "staging_db",
  "logLevel": "info"
}
Code
JSON
// Production Environment
{
  "baseUrl": "https://api.example.com",
  "authToken": "{{ process.env.PROD_API_TOKEN }}",
  "debugMode": false,
  "database": "prod_db",
  "logLevel": "error"
}

Użycie zmiennych

Code
TEXT
# W URL
URL: {{ _.baseUrl }}/{{ _.apiVersion }}/users

# W Headers
Authorization: Bearer {{ _.authToken }}
X-Debug-Mode: {{ _.debugMode }}

# W Body
{
  "config": {
    "database": "{{ _.database }}",
    "timeout": {{ _.timeout }}
  }
}

# Zmienne środowiskowe systemu
{{ process.env.API_KEY }}

# Timestamp
{{ timestamp }}

# UUID
{{ uuid }}

Dynamic Variables (Template Tags)

Code
JavaScript
// Wbudowane template tags w Insomnia:

{{ timestamp }}           // Unix timestamp: 1706180000
{{ timestamp:iso }}       // ISO date: 2025-01-25T10:30:00.000Z
{{ uuid }}                // UUID v4: f47ac10b-58cc-4372-a567-0e02b2c3d479
{{ base64:encode }}       // Base64 encode
{{ base64:decode }}       // Base64 decode
{{ hash:sha256 }}         // SHA256 hash
{{ now:YYYY-MM-DD }}      // Formatted date

// Response reference (dla chaining)
{% response 'body', 'req_login', '$.token' %}
{% response 'header', 'req_login', 'X-Request-Id' %}
{% response 'status', 'req_login' %}

// Prompt (zapytaj użytkownika)
{% prompt 'Enter API Key', 'api-key', false %}

// File (załaduj z pliku)
{% file './data/payload.json' %}

Request Chaining

Automatyczne przekazywanie tokenów

Code
JavaScript
// Scenariusz: Login → Profile → Update

// 1. Login Request
POST {{ _.baseUrl }}/auth/login
Body: { "email": "user@example.com", "password": "secret" }
// Response: { "token": "jwt_token_here", "refreshToken": "refresh_here" }

// 2. Profile Request (używa tokena z Login)
GET {{ _.baseUrl }}/users/me
Headers:
  Authorization: Bearer {% response 'body', 'req_login', '$.token' %}

// 3. Update Request (używa userId z Profile)
PATCH {{ _.baseUrl }}/users/{% response 'body', 'req_profile', '$.id' %}
Headers:
  Authorization: Bearer {% response 'body', 'req_login', '$.token' %}
Body: { "name": "Updated Name" }

Chaining z JSONPath

Code
JavaScript
// Response z pierwszego requestu:
{
  "data": {
    "user": {
      "id": "user_123",
      "profile": {
        "settings": {
          "theme": "dark",
          "notifications": true
        }
      }
    }
  }
}

// JSONPath expressions:
{% response 'body', 'req_1', '$.data.user.id' %}
// Wynik: "user_123"

{% response 'body', 'req_1', '$.data.user.profile.settings.theme' %}
// Wynik: "dark"

{% response 'body', 'req_1', '$.data.user.profile.settings.*' %}
// Wynik: ["dark", true]

Environment chaining

Code
JSON
// Environment z dynamic values
{
  "authToken": "{% response 'body', 'req_login', '$.token' %}",
  "userId": "{% response 'body', 'req_login', '$.user.id' %}",
  "sessionId": "{% response 'header', 'req_login', 'X-Session-Id' %}"
}

// Teraz wszystkie requesty używają tych wartości:
Authorization: Bearer {{ _.authToken }}
X-User-Id: {{ _.userId }}
X-Session-Id: {{ _.sessionId }}

GraphQL

Query

Code
GraphQL
# Endpoint: {{ _.baseUrl }}/graphql

query GetUsers($first: Int!, $after: String) {
  users(first: $first, after: $after) {
    edges {
      node {
        id
        name
        email
        avatar
        createdAt
      }
      cursor
    }
    pageInfo {
      hasNextPage
      endCursor
    }
  }
}

# Variables
{
  "first": 10,
  "after": null
}

Mutation

Code
GraphQL
mutation CreateUser($input: CreateUserInput!) {
  createUser(input: $input) {
    user {
      id
      name
      email
    }
    errors {
      field
      message
    }
  }
}

# Variables
{
  "input": {
    "name": "Jan Kowalski",
    "email": "jan@example.com",
    "password": "securePassword123"
  }
}

Subscription

Code
GraphQL
# Insomnia obsługuje GraphQL subscriptions przez WebSocket

subscription OnMessageReceived($channelId: ID!) {
  messageReceived(channelId: $channelId) {
    id
    content
    sender {
      name
      avatar
    }
    createdAt
  }
}

# Variables
{
  "channelId": "channel_123"
}

# Insomnia automatycznie nawiązuje połączenie WebSocket
# i wyświetla przychodzące wiadomości

Auto-complete i Schema

Code
GraphQL
# Insomnia automatycznie pobiera schema z:
# - Introspection query
# - URL do schema file
# - Lokalny plik .graphql

# Dzięki temu masz:
# - Autocomplete dla pól i typów
# - Walidację query w czasie rzeczywistym
# - Dokumentację inline
# - Podpowiedzi argumentów

gRPC Testing

Konfiguracja

Code
TEXT
# Metoda 1: Reflection (automatyczne)
Server URL: grpc.example.com:443
Use Server Reflection: Yes

# Metoda 2: Proto file
Server URL: grpc.example.com:443
Proto File: ./protos/service.proto

# Metoda 3: Proto directory
Server URL: grpc.example.com:443
Proto Directory: ./protos/

Unary Call

user_service.proto
PROTOBUF
// user_service.proto
service UserService {
  rpc GetUser (GetUserRequest) returns (User);
  rpc CreateUser (CreateUserRequest) returns (User);
}

message GetUserRequest {
  string id = 1;
}

message User {
  string id = 1;
  string name = 2;
  string email = 3;
  int32 age = 4;
}
Code
JSON
// Request (Insomnia)
Service: UserService
Method: GetUser

Message:
{
  "id": "user_123"
}

// Response
{
  "id": "user_123",
  "name": "Jan Kowalski",
  "email": "jan@example.com",
  "age": 30
}

Server Streaming

Code
PROTOBUF
service StreamService {
  rpc StreamEvents (StreamRequest) returns (stream Event);
}

message StreamRequest {
  string channel = 1;
}

message Event {
  string id = 1;
  string type = 2;
  string data = 3;
  int64 timestamp = 4;
}
Code
JSON
// Request
{
  "channel": "notifications"
}

// Streaming responses (wyświetlane w czasie rzeczywistym)
{"id":"1","type":"message","data":"Hello","timestamp":1706180000}
{"id":"2","type":"notification","data":"Update","timestamp":1706180001}
{"id":"3","type":"alert","data":"Warning","timestamp":1706180002}

Bidirectional Streaming

Code
PROTOBUF
service ChatService {
  rpc Chat (stream ChatMessage) returns (stream ChatMessage);
}

message ChatMessage {
  string user = 1;
  string content = 2;
  int64 timestamp = 3;
}
Code
JSON
// Wysyłaj wiadomości
{"user":"jan","content":"Hello!","timestamp":1706180000}
{"user":"jan","content":"Anyone there?","timestamp":1706180005}

// Odbieraj odpowiedzi
{"user":"anna","content":"Hi Jan!","timestamp":1706180002}
{"user":"anna","content":"Yes, I'm here","timestamp":1706180007}

API Design (OpenAPI)

Tworzenie specyfikacji

Code
YAML
# Insomnia Design View

openapi: 3.1.0
info:
  title: My API
  version: 1.0.0
  description: |
    API dla aplikacji e-commerce.
    Obsługuje użytkowników, produkty i zamówienia.
  contact:
    name: API Support
    email: api@example.com

servers:
  - url: https://api.example.com/v1
    description: Production
  - url: https://staging-api.example.com/v1
    description: Staging
  - url: http://localhost:3000/v1
    description: Development

paths:
  /users:
    get:
      summary: Lista użytkowników
      operationId: listUsers
      tags:
        - Users
      parameters:
        - name: page
          in: query
          schema:
            type: integer
            default: 1
        - name: limit
          in: query
          schema:
            type: integer
            default: 20
            maximum: 100
      responses:
        '200':
          description: Lista użytkowników
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/UserList'

    post:
      summary: Utwórz użytkownika
      operationId: createUser
      tags:
        - Users
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/CreateUserInput'
      responses:
        '201':
          description: Użytkownik utworzony
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/User'

  /users/{id}:
    get:
      summary: Pobierz użytkownika
      operationId: getUser
      tags:
        - Users
      parameters:
        - name: id
          in: path
          required: true
          schema:
            type: string
      responses:
        '200':
          description: Dane użytkownika
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/User'
        '404':
          description: Użytkownik nie znaleziony

components:
  schemas:
    User:
      type: object
      properties:
        id:
          type: string
          format: uuid
        name:
          type: string
        email:
          type: string
          format: email
        createdAt:
          type: string
          format: date-time
      required:
        - id
        - name
        - email

    CreateUserInput:
      type: object
      properties:
        name:
          type: string
          minLength: 2
          maxLength: 100
        email:
          type: string
          format: email
        password:
          type: string
          minLength: 8
      required:
        - name
        - email
        - password

    UserList:
      type: object
      properties:
        users:
          type: array
          items:
            $ref: '#/components/schemas/User'
        total:
          type: integer
        page:
          type: integer
        limit:
          type: integer

  securitySchemes:
    bearerAuth:
      type: http
      scheme: bearer
      bearerFormat: JWT

security:
  - bearerAuth: []

Generowanie requestów z OpenAPI

Code
TEXT
# Po zdefiniowaniu OpenAPI spec, Insomnia automatycznie:

1. Generuje Collection z wszystkimi endpoints
2. Tworzy przykładowe requesty
3. Ustawia validation na podstawie schemas
4. Generuje dokumentację
5. Tworzy mock server (preview)

# Możesz też importować istniejące spec:
File → Import → OpenAPI/Swagger

Testing w Insomnia

Basic Test Scripts

Code
JavaScript
// Test script (JavaScript)
// Wykonuje się po każdym response

// Sprawdź status code
const response = insomnia.response;

if (response.status !== 200) {
  throw new Error(`Expected 200, got ${response.status}`);
}

// Sprawdź body
const body = JSON.parse(response.body);

if (!body.users || !Array.isArray(body.users)) {
  throw new Error('Expected users array in response');
}

if (body.users.length === 0) {
  throw new Error('Expected at least one user');
}

// Sprawdź strukturę
const user = body.users[0];
const requiredFields = ['id', 'name', 'email'];

for (const field of requiredFields) {
  if (!user[field]) {
    throw new Error(`Missing required field: ${field}`);
  }
}

// Sprawdź response time
if (response.responseTime > 1000) {
  throw new Error(`Response too slow: ${response.responseTime}ms`);
}

console.log('All tests passed!');

Assertions z Chai

Code
JavaScript
// Insomnia wspiera Chai assertions

const { expect } = require('chai');

const response = insomnia.response;
const body = JSON.parse(response.body);

// Status assertions
expect(response.status).to.equal(200);
expect(response.status).to.be.within(200, 299);

// Body assertions
expect(body).to.have.property('users');
expect(body.users).to.be.an('array');
expect(body.users).to.have.lengthOf.at.least(1);

// User structure
const user = body.users[0];
expect(user).to.include.all.keys('id', 'name', 'email');
expect(user.email).to.match(/^[^\s@]+@[^\s@]+\.[^\s@]+$/);

// Headers
expect(response.headers).to.have.property('content-type');
expect(response.headers['content-type']).to.include('application/json');

// Response time
expect(response.responseTime).to.be.below(500);

Collection Runner

Code
Bash
# Uruchom wszystkie testy w kolekcji

# Z GUI:
# 1. Otwórz Collection
# 2. Kliknij "Run" button
# 3. Wybierz Environment
# 4. Kliknij "Run Tests"

# Z CLI (Inso):
npm install -g insomnia-inso

# Uruchom testy
inso run test "My Collection" --env "Production"

# Output:
# Running tests for "My Collection"
#   ✓ GET /users (234ms)
#   ✓ POST /users (456ms)
#   ✓ GET /users/:id (123ms)
#   ✗ DELETE /users/:id (89ms)
#     Error: Expected 204, got 403
#
# Results: 3 passed, 1 failed

CI/CD Integration

.github/workflows/api-tests.yml
YAML
# .github/workflows/api-tests.yml
name: API Tests

on:
  push:
    branches: [main]
  pull_request:
    branches: [main]
  schedule:
    - cron: '0 */6 * * *'  # Co 6 godzin

jobs:
  test:
    runs-on: ubuntu-latest

    steps:
      - uses: actions/checkout@v4

      - name: Setup Node.js
        uses: actions/setup-node@v4
        with:
          node-version: '20'

      - name: Install Inso CLI
        run: npm install -g insomnia-inso

      - name: Run API Tests
        run: |
          inso run test "API Tests" \
            --src insomnia.yaml \
            --env "CI Environment" \
            --reporter junit \
            --output test-results.xml
        env:
          API_BASE_URL: ${{ secrets.API_BASE_URL }}
          API_TOKEN: ${{ secrets.API_TOKEN }}

      - name: Upload Test Results
        uses: actions/upload-artifact@v4
        if: always()
        with:
          name: test-results
          path: test-results.xml

      - name: Publish Test Report
        uses: mikepenz/action-junit-report@v4
        if: always()
        with:
          report_paths: test-results.xml

Plugins

Instalacja pluginów

Code
Bash
# Insomnia Plugin Hub
# Preferences → Plugins → Browse Plugins

# Popularne pluginy:
# - insomnia-plugin-jwt - Dekodowanie JWT
# - insomnia-plugin-hash - Hashing functions
# - insomnia-plugin-file - File operations
# - insomnia-plugin-random - Random data generators
# - insomnia-plugin-base64 - Base64 encode/decode

Tworzenie własnych pluginów

JSinsomnia-plugin-custom-auth/main.js
JavaScript
// insomnia-plugin-custom-auth/main.js

module.exports.templateTags = [
  {
    name: 'customAuth',
    displayName: 'Custom Auth Token',
    description: 'Generates custom authentication token',

    args: [
      {
        displayName: 'API Key',
        type: 'string',
        defaultValue: ''
      },
      {
        displayName: 'Secret',
        type: 'string',
        defaultValue: ''
      }
    ],

    async run(context, apiKey, secret) {
      const crypto = require('crypto');
      const timestamp = Date.now().toString();
      const message = `${apiKey}:${timestamp}`;

      const hmac = crypto.createHmac('sha256', secret);
      hmac.update(message);
      const signature = hmac.digest('hex');

      return `${apiKey}:${timestamp}:${signature}`;
    }
  }
];

// Użycie w Insomnia:
// Authorization: {% customAuth 'my-api-key', 'my-secret' %}
insomnia-plugin-custom-auth/package.json
JSON
// insomnia-plugin-custom-auth/package.json
{
  "name": "insomnia-plugin-custom-auth",
  "version": "1.0.0",
  "insomnia": {
    "name": "custom-auth",
    "displayName": "Custom Auth Plugin",
    "description": "Generates custom HMAC-based auth tokens"
  },
  "main": "main.js"
}

Request/Response Hooks

JSinsomnia-plugin-logger/main.js
JavaScript
// insomnia-plugin-logger/main.js

module.exports.requestHooks = [
  (context) => {
    const { request } = context;

    // Log request details
    console.log(`[REQUEST] ${request.method} ${request.url}`);
    console.log('[HEADERS]', JSON.stringify(request.headers, null, 2));

    if (request.body && request.body.text) {
      console.log('[BODY]', request.body.text);
    }

    // Modify request
    request.setHeader('X-Request-Id', generateUUID());
    request.setHeader('X-Timestamp', Date.now().toString());
  }
];

module.exports.responseHooks = [
  (context) => {
    const { response } = context;

    // Log response
    console.log(`[RESPONSE] ${response.status} ${response.statusText}`);
    console.log(`[TIME] ${response.elapsedTime}ms`);

    // Check for errors
    if (response.status >= 400) {
      console.error('[ERROR]', response.body);
    }
  }
];

function generateUUID() {
  return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {
    const r = Math.random() * 16 | 0;
    const v = c === 'x' ? r : (r & 0x3 | 0x8);
    return v.toString(16);
  });
}

Inso CLI

Instalacja

Code
Bash
# npm
npm install -g insomnia-inso

# Homebrew (macOS)
brew install inso

# Sprawdź wersję
inso --version

Podstawowe komendy

Code
Bash
# Eksportuj spec do pliku
inso export spec "My API" --output api-spec.yaml

# Lint OpenAPI spec
inso lint spec api-spec.yaml

# Uruchom testy
inso run test "API Tests" --env "Production"

# Generuj konfigurację Kong
inso generate config "My API" --type kong --output kong.yaml

# Script mode (z pliku)
inso script run my-script

Integracja z Kong Gateway

Code
Bash
# Generuj konfigurację Kong z OpenAPI
inso generate config "My API" \
  --type kong \
  --output kong.yaml

# Wygenerowany kong.yaml:
kong.yaml
YAML
# kong.yaml
_format_version: "2.1"
services:
  - name: my-api
    url: https://api.example.com
    routes:
      - name: users-list
        paths:
          - /v1/users
        methods:
          - GET
        strip_path: false
      - name: users-create
        paths:
          - /v1/users
        methods:
          - POST
        strip_path: false
    plugins:
      - name: rate-limiting
        config:
          minute: 100
      - name: jwt

Git Sync

Konfiguracja Git Sync

Code
Bash
# 1. Utwórz nowy projekt w Insomnia
# 2. Kliknij "Setup Git Sync"
# 3. Podaj URL repozytorium:
#    git@github.com:username/api-collection.git

# Struktura repozytorium:
api-collection/
├── .insomnia/
│   ├── ApiSpec/
│   │   └── spc_xxx.yml        # OpenAPI specs
│   ├── Environment/
│   │   ├── env_base.json      # Base environment
│   │   ├── env_dev.json       # Dev environment
│   │   └── env_prod.json      # Prod environment
│   ├── Request/
│   │   ├── req_login.json     # Login request
│   │   ├── req_users.json     # Users request
│   │   └── req_products.json  # Products request
│   ├── RequestGroup/
│   │   ├── fld_auth.json      # Auth folder
│   │   └── fld_api.json       # API folder
│   └── Workspace/
│       └── wrk_main.json      # Main workspace
└── README.md

Workflow zespołowy

Code
Bash
# Developer 1: Dodaje nowy endpoint
# 1. Pull najnowsze zmiany
git pull origin main

# 2. Utwórz branch
git checkout -b feature/add-orders-endpoint

# 3. Edytuj w Insomnia (automatyczny sync)

# 4. Commit i push
git add .
git commit -m "Add orders endpoint"
git push origin feature/add-orders-endpoint

# 5. Utwórz Pull Request

# Developer 2: Review i merge
# 1. Pull branch
git fetch origin
git checkout feature/add-orders-endpoint

# 2. Otwórz w Insomnia i testuj

# 3. Merge po approval
git checkout main
git merge feature/add-orders-endpoint
git push origin main

# Wszyscy: Sync
# Insomnia automatycznie wykrywa zmiany i synchronizuje

Authentication

Basic Auth

Code
TEXT
Authorization Type: Basic Auth
Username: api_user
Password: api_secret

# Insomnia generuje:
Authorization: Basic YXBpX3VzZXI6YXBpX3NlY3JldA==

Bearer Token

Code
TEXT
Authorization Type: Bearer Token
Token: {{ _.authToken }}

# Header:
Authorization: Bearer eyJhbGciOiJIUzI1NiIs...

OAuth 2.0

Code
TEXT
Authorization Type: OAuth 2.0

# Grant Type: Authorization Code
Authorization URL: https://auth.example.com/authorize
Token URL: https://auth.example.com/token
Client ID: {{ _.clientId }}
Client Secret: {{ _.clientSecret }}
Redirect URL: insomnia://oauth/callback
Scope: read write profile

# Insomnia przeprowadza flow automatycznie:
# 1. Otwiera przeglądarkę dla autoryzacji
# 2. Odbiera callback z kodem
# 3. Wymienia kod na token
# 4. Używa tokena w requestach

AWS Signature

Code
TEXT
Authorization Type: AWS IAM v4

Access Key ID: {{ _.awsAccessKey }}
Secret Access Key: {{ _.awsSecretKey }}
Region: eu-central-1
Service: execute-api

# Opcjonalnie:
Session Token: {{ _.awsSessionToken }}

# Insomnia automatycznie generuje:
# - Authorization header (AWS4-HMAC-SHA256)
# - X-Amz-Date
# - X-Amz-Security-Token (jeśli używasz STS)

Digest Auth

Code
TEXT
Authorization Type: Digest Auth
Username: api_user
Password: api_secret

# Insomnia automatycznie:
# 1. Wysyła request bez auth
# 2. Odbiera WWW-Authenticate challenge
# 3. Oblicza response hash
# 4. Wysyła request z Digest auth

Keyboard Shortcuts

Code
Bash
# Request
Ctrl/Cmd + Enter    # Wyślij request
Ctrl/Cmd + Shift + Enter  # Wyślij i pobierz response
Ctrl/Cmd + R        # Refresh/Resend

# Navigation
Ctrl/Cmd + 1-9      # Switch między requestami
Ctrl/Cmd + E        # Toggle Environment selector
Ctrl/Cmd + Shift + E  # Manage Environments
Ctrl/Cmd + P        # Quick switch (fuzzy search)

# Edit
Ctrl/Cmd + D        # Duplikuj request
Ctrl/Cmd + Shift + D  # Duplikuj folder
Ctrl/Cmd + Delete   # Usuń request
Ctrl/Cmd + N        # Nowy request
Ctrl/Cmd + Shift + N  # Nowy folder

# View
Ctrl/Cmd + \        # Toggle sidebar
Ctrl/Cmd + Shift + \  # Toggle response panel
Ctrl/Cmd + ,        # Preferences
F11                 # Fullscreen

# Format
Ctrl/Cmd + Shift + F  # Format JSON/XML
Tab                 # Indent
Shift + Tab         # Outdent

Cennik

Insomnia Free (Scratch Pad)

CechaDostępność
REST/GraphQL/gRPC
WebSocket
OpenAPI Design
Environments
Plugins
Local storage
Cloud sync
Team collaboration

Insomnia Individual

CechaCena: $5/miesiąc
Wszystko z Free
Cloud sync
End-to-end encryption
Unlimited devices

Insomnia Team

CechaCena: $12/user/miesiąc
Wszystko z Individual
Team workspaces
Role-based access
Shared environments
Git Sync (built-in)

Insomnia Enterprise

CechaCustom pricing
Wszystko z Team
SSO/SAML
Audit logs
Advanced security
Dedicated support
On-premise option

FAQ - Najczęściej zadawane pytania

Czy Insomnia jest darmowa?

Tak, Insomnia oferuje darmowy plan "Scratch Pad" z pełną funkcjonalnością dla lokalnego użytku. Dane są przechowywane tylko lokalnie, bez synchronizacji między urządzeniami. Płatne plany dodają cloud sync i funkcje zespołowe.

Jak przejść z Postmana do Insomnia?

Insomnia obsługuje import kolekcji Postmana. Eksportuj kolekcję z Postmana jako JSON (Collection v2.1) i zaimportuj w Insomnia przez File → Import. Większość requestów, środowisk i zmiennych zostanie przeniesiona automatycznie.

Czy mogę używać Insomnia offline?

Tak, w trybie Scratch Pad Insomnia działa całkowicie offline. Wszystkie dane są przechowywane lokalnie. Dla płatnych planów z cloud sync, requesty działają offline, a synchronizacja następuje po połączeniu z internetem.

Jak zabezpieczyć wrażliwe dane?

  1. Scratch Pad - dane tylko lokalnie, pełna kontrola
  2. Cloud Sync - end-to-end encryption, dane szyfrowane przed wysłaniem
  3. Git Sync - używaj własnego prywatnego repozytorium
  4. Environment variables - przechowuj sekrety w oddzielnym pliku .env

Czy Insomnia obsługuje GraphQL introspection?

Tak, Insomnia automatycznie wykonuje introspection query i pobiera schema z serwera GraphQL. Dzięki temu masz autocomplete, walidację i dokumentację pól bezpośrednio w edytorze.

Jak udostępnić kolekcje zespołowi bez płatnego planu?

Użyj Git Sync - jest dostępny nawet w darmowej wersji. Eksportuj projekt jako Git repository i udostępnij przez GitHub, GitLab lub Bitbucket. Każdy członek zespołu może sklonować repo i otworzyć w swojej Insomnia.

Czy mogę zintegrować Insomnia z CI/CD?

Tak, użyj Inso CLI. Możesz uruchamiać testy API, generować konfiguracje Kong Gateway i eksportować specyfikacje OpenAPI jako część pipeline'u CI/CD.

Podsumowanie

Insomnia to profesjonalny API client od Kong, który łączy elegancki design z pełną funkcjonalnością. Dzięki błyskawicznemu startowi, niskiemu zużyciu zasobów i natywnej obsłudze OpenAPI, jest idealnym wyborem dla deweloperów szukających wydajnej alternatywy dla Postmana.

Główne zalety Insomnia:

  • Szybkość - start w ułamku sekundy, niskie zużycie RAM
  • OpenAPI native - projektuj API wizualnie, generuj requesty
  • Request chaining - automatyczne przekazywanie danych
  • Git Sync - współpraca zespołowa bez vendor lock-in
  • Plugin system - rozszerzaj funkcjonalność
  • Scratch Pad - pełna funkcjonalność bez konta

Czy to do codziennego testowania API, projektowania nowych endpoints, czy automatyzacji testów w CI/CD - Insomnia dostarcza wszystko czego potrzebujesz w eleganckim, wydajnym pakiecie.