Elysia Tools

Durchsuche Tools, Beispiele, visuelle Erklärungen und Themenguides an einem klaren Ort.

Beliebte Kategorien

Themen

Sprache
ZHESPTRUFRDEEN

Elysia Tools

Mobile Navigation

Testen

Postman Collections - API Tests

Umfassende Postman Collection Beispiele inklusive API Tests, Automatisierungsskripte, Umgebungsvariablen, Mock Server und fortgeschrittene Testmuster für REST APIs

Beispiele

Einträge in dieser Sammlung

QuellcodejsonEinfach

Postman Basis Collection Setup

Vollständige Postman Collection Einrichtung mit Umgebungsvariablen, Authentifizierung und grundlegenden API Test Mustern

Schwierigkeit

3/10

Geschätzte Zeit

25 min

Schlagwörter

postman, api testing, collections, automation

Voraussetzungen

REST API concepts, HTTP methods, JSON format

json
{
  "info": {
    "name": "E-Commerce API",
    "description": "A comprehensive collection for testing e-commerce REST API endpoints",
    "version": "1.0.0",
    "schema": "https://schema.getpostman.com/json/collection/v2.1.0/collection.json"
  },
  "item": [
    {
      "name": "Authentication",
      "item": [
        {
          "name": "User Login",
          "event": [
            {
              "listen": "test",
              "script": {
                "exec": [
                  "// Test response status and structure",
                  "pm.test('Status code is 200', function () {",
                  "    pm.response.to.have.status(200);",
                  "});",
                  "",
                  "pm.test('Response has token', function () {",
                  "    const jsonData = pm.response.json();",
                  "    pm.expect(jsonData).to.have.property('token');",
                  "    pm.expect(jsonData).to.have.property('user');",
                  "});",
                  "",
                  "// Set environment variables for authentication",
                  "if (pm.response.code === 200) {",
                  "    const jsonData = pm.response.json();",
                  "    pm.environment.set('auth_token', jsonData.token);",
                  "    pm.environment.set('user_id', jsonData.user.id);",
                  "    pm.environment.set('user_email', jsonData.user.email);",
                  "    ",
                  "    // Set token expiration (assuming 24 hours)",
                  "    const expiresAt = Date.now() + (24 * 60 * 60 * 1000);",
                  "    pm.environment.set('token_expires_at', expiresAt.toString());",
                  "}",
                  "",
                  "// Log successful authentication",
                  "console.log('User authenticated successfully:', pm.environment.get('user_email'));"
                ],
                "type": "text/javascript"
              }
            }
          ],
          "request": {
            "method": "POST",
            "header": [
              {
                "key": "Content-Type",
                "value": "application/json"
              }
            ],
            "body": {
              "mode": "raw",
              "raw": "{\n  \"email\": \"{{admin_email}}\",\n  \"password\": \"{{admin_password}}\"\n}"
            },
            "url": {
              "raw": "{{base_url}}/api/auth/login",
              "host": ["{{base_url}}"],
              "path": ["api", "auth", "login"]
            }
          }
        },
        {
          "name": "User Registration",
          "event": [
            {
              "listen": "test",
              "script": {
                "exec": [
                  "pm.test('Status code is 201', function () {",
                  "    pm.response.to.have.status(201);",
                  "});",
                  "",
                  "pm.test('Response has user data', function () {",
                  "    const jsonData = pm.response.json();",
                  "    pm.expect(jsonData).to.have.property('user');",
                  "    pm.expect(jsonData.user).to.have.property('id');",
                  "    pm.expect(jsonData.user).to.have.property('email');",
                  "    pm.expect(jsonData.user.email).to.eql(pm.request.body.raw);",
                  "});",
                  "",
                  "pm.test('Password is not returned in response', function () {",
                  "    const jsonData = pm.response.json();",
                  "    pm.expect(jsonData.user).to.not.have.property('password');",
                  "});"
                ],
                "type": "text/javascript"
              }
            }
          ],
          "request": {
            "method": "POST",
            "header": [
              {
                "key": "Content-Type",
                "value": "application/json"
              }
            ],
            "body": {
              "mode": "raw",
              "raw": "{\n  \"username\": \"{{$randomUserName}}\",\n  \"email\": \"{{$randomEmail}}\",\n  \"password\": \"{{$randomPassword}}\",\n  \"firstName\": \"{{$randomFirstName}}\",\n  \"lastName\": \"{{$randomLastName}}\"\n}"
            },
            "url": {
              "raw": "{{base_url}}/api/auth/register",
              "host": ["{{base_url}}"],
              "path": ["api", "auth", "register"]
            }
          }
        },
        {
          "name": "Refresh Token",
          "event": [
            {
              "listen": "prerequest",
              "script": {
                "exec": [
                  "// Check if token is expired",
                  "const expiresAt = pm.environment.get('token_expires_at');",
                  "if (expiresAt && Date.now() > parseInt(expiresAt)) {",
                  "    console.log('Token expired, skipping refresh request');",
                  "    // Skip this request if token is expired",
                  "    postman.setNextRequest(null);",
                  "} else {",
                  "    console.log('Token valid, proceeding with refresh');",
                  "}"
                ],
                "type": "text/javascript"
              }
            },
            {
              "listen": "test",
              "script": {
                "exec": [
                  "pm.test('Status code is 200', function () {",
                  "    pm.response.to.have.status(200);",
                  "});",
                  "",
                  "pm.test('New token received', function () {",
                  "    const jsonData = pm.response.json();",
                  "    pm.expect(jsonData).to.have.property('token');",
                  "    ",
                  "    // Update environment with new token",
                  "    if (jsonData.token) {",
                  "        pm.environment.set('auth_token', jsonData.token);",
                  "        const expiresAt = Date.now() + (24 * 60 * 60 * 1000);",
                  "        pm.environment.set('token_expires_at', expiresAt.toString());",
                  "    }",
                  "});"
                ],
                "type": "text/javascript"
              }
            }
          ],
          "request": {
            "method": "POST",
            "header": [
              {
                "key": "Authorization",
                "value": "Bearer {{auth_token}}"
              }
            ],
            "url": {
              "raw": "{{base_url}}/api/auth/refresh",
              "host": ["{{base_url}}"],
              "path": ["api", "auth", "refresh"]
            }
          }
        }
      ]
    },
    {
      "name": "Products",
      "item": [
        {
          "name": "Get All Products",
          "event": [
            {
              "listen": "test",
              "script": {
                "exec": [
                  "pm.test('Status code is 200', function () {",
                  "    pm.response.to.have.status(200);",
                  "});",
                  "",
                  "pm.test('Response is an array', function () {",
                  "    const jsonData = pm.response.json();",
                  "    pm.expect(jsonData).to.be.an('array');",
                  "});",
                  "",
                  "pm.test('Products have required fields', function () {",
                  "    const jsonData = pm.response.json();",
                  "    if (jsonData.length > 0) {",
                  "        jsonData.forEach(product => {",
                  "            pm.expect(product).to.have.property('id');",
                  "            pm.expect(product).to.have.property('name');",
                  "            pm.expect(product).to.have.property('price');",
                  "            pm.expect(product).to.have.property('description');",
                  "        });",
                  "    }",
                  "});",
                  "",
                  "// Store first product ID for later use",
                  "if (pm.response.code === 200) {",
                  "    const jsonData = pm.response.json();",
                  "    if (jsonData.length > 0) {",
                  "        pm.environment.set('product_id', jsonData[0].id);",
                  "    }",
                  "}"
                ],
                "type": "text/javascript"
              }
            }
          ],
          "request": {
            "method": "GET",
            "url": {
              "raw": "{{base_url}}/api/products?page={{page}}&limit={{limit}}&category={{category}}",
              "host": ["{{base_url}}"],
              "path": ["api", "products"],
              "query": [
                {
                  "key": "page",
                  "value": "{{page}}",
                  "description": "Page number for pagination"
                },
                {
                  "key": "limit",
                  "value": "{{limit}}",
                  "description": "Number of items per page"
                },
                {
                  "key": "category",
                  "value": "{{category}}",
                  "description": "Filter by category",
                  "disabled": true
                }
              ]
            }
          }
        },
        {
          "name": "Get Product by ID",
          "event": [
            {
              "listen": "test",
              "script": {
                "exec": [
                  "pm.test('Status code is 200', function () {",
                  "    pm.response.to.have.status(200);",
                  "});",
                  "",
                  "pm.test('Product has required fields', function () {",
                  "    const jsonData = pm.response.json();",
                  "    pm.expect(jsonData).to.have.property('id');",
                  "    pm.expect(jsonData).to.have.property('name');",
                  "    pm.expect(jsonData).to.have.property('price');",
                  "    pm.expect(jsonData).to.have.property('description');",
                  "    pm.expect(jsonData).to.have.property('category');",
                  "    pm.expect(jsonData).to.have.property('stock');",
                  "});",
                  "",
                  "pm.test('Price is a positive number', function () {",
                  "    const jsonData = pm.response.json();",
                  "    pm.expect(jsonData.price).to.be.a('number');",
                  "    pm.expect(jsonData.price).to.be.above(0);",
                  "});",
                  "",
                  "pm.test('Stock is a non-negative integer', function () {",
                  "    const jsonData = pm.response.json();",
                  "    pm.expect(jsonData.stock).to.be.a('number');",
                  "    pm.expect(jsonData.stock).to.be.at.least(0);",
                  "});"
                ],
                "type": "text/javascript"
              }
            }
          ],
          "request": {
            "method": "GET",
            "url": {
              "raw": "{{base_url}}/api/products/{{product_id}}",
              "host": ["{{base_url}}"],
              "path": ["api", "products", "{{product_id}}"]
            }
          }
        },
        {
          "name": "Create Product",
          "event": [
            {
              "listen": "test",
              "script": {
                "exec": [
                  "pm.test('Status code is 201', function () {",
                  "    pm.response.to.have.status(201);",
                  "});",
                  "",
                  "pm.test('Product created successfully', function () {",
                  "    const jsonData = pm.response.json();",
                  "    pm.expect(jsonData).to.have.property('id');",
                  "    pm.expect(jsonData).to.have.property('name');",
                  "    pm.expect(jsonData.name).to.eql(JSON.parse(pm.request.body.raw).name);",
                  "});",
                  "",
                  "// Store new product ID",
                  "if (pm.response.code === 201) {",
                  "    const jsonData = pm.response.json();",
                  "    pm.environment.set('new_product_id', jsonData.id);",
                  "}"
                ],
                "type": "text/javascript"
              }
            }
          ],
          "request": {
            "method": "POST",
            "header": [
              {
                "key": "Content-Type",
                "value": "application/json"
              },
              {
                "key": "Authorization",
                "value": "Bearer {{auth_token}}"
              }
            ],
            "body": {
              "mode": "raw",
              "raw": "{\n  \"name\": \"Test Product {{$randomInt}}\",\n  \"description\": \"This is a test product created via API\",\n  \"price\": {{$randomPrice}},\n  \"category\": \"electronics\",\n  \"stock\": {{$randomStock}}\n}"
            },
            "url": {
              "raw": "{{base_url}}/api/products",
              "host": ["{{base_url}}"],
              "path": ["api", "products"]
            }
          }
        }
      ]
    },
    {
      "name": "Orders",
      "item": [
        {
          "name": "Create Order",
          "event": [
            {
              "listen": "test",
              "script": {
                "exec": [
                  "pm.test('Status code is 201', function () {",
                  "    pm.response.to.have.status(201);",
                  "});",
                  "",
                  "pm.test('Order created with required fields', function () {",
                  "    const jsonData = pm.response.json();",
                  "    pm.expect(jsonData).to.have.property('id');",
                  "    pm.expect(jsonData).to.have.property('userId');",
                  "    pm.expect(jsonData).to.have.property('items');",
                  "    pm.expect(jsonData).to.have.property('totalAmount');",
                  "    pm.expect(jsonData).to.have.property('status');",
                  "});",
                  "",
                  "pm.test('Order status is pending', function () {",
                  "    const jsonData = pm.response.json();",
                  "    pm.expect(jsonData.status).to.eql('pending');",
                  "});",
                  "",
                  "// Store order ID for later use",
                  "if (pm.response.code === 201) {",
                  "    const jsonData = pm.response.json();",
                  "    pm.environment.set('order_id', jsonData.id);",
                  "}"
                ],
                "type": "text/javascript"
              }
            }
          ],
          "request": {
            "method": "POST",
            "header": [
              {
                "key": "Content-Type",
                "value": "application/json"
              },
              {
                "key": "Authorization",
                "value": "Bearer {{auth_token}}"
              }
            ],
            "body": {
              "mode": "raw",
              "raw": "{\n  \"items\": [\n    {\n      \"productId\": \"{{product_id}}\",\n      \"quantity\": 2,\n      \"price\": 29.99\n    }\n  ],\n  \"shippingAddress\": {\n    \"street\": \"123 Test Street\",\n    \"city\": \"Test City\",\n    \"state\": \"TS\",\n    \"zipCode\": \"12345\",\n    \"country\": \"US\"\n  }\n}"
            },
            "url": {
              "raw": "{{base_url}}/api/orders",
              "host": ["{{base_url}}"],
              "path": ["api", "orders"]
            }
          }
        },
        {
          "name": "Get Order by ID",
          "event": [
            {
              "listen": "test",
              "script": {
                "exec": [
                  "pm.test('Status code is 200', function () {",
                  "    pm.response.to.have.status(200);",
                  "});",
                  "",
                  "pm.test('Order belongs to authenticated user', function () {",
                  "    const jsonData = pm.response.json();",
                  "    pm.expect(jsonData.userId).to.eql(pm.environment.get('user_id'));",
                  "});",
                  "",
                  "pm.test('Order has items array', function () {",
                  "    const jsonData = pm.response.json();",
                  "    pm.expect(jsonData.items).to.be.an('array');",
                  "    pm.expect(jsonData.items.length).to.be.above(0);",
                  "});"
                ],
                "type": "text/javascript"
              }
            }
          ],
          "request": {
            "method": "GET",
            "header": [
              {
                "key": "Authorization",
                "value": "Bearer {{auth_token}}"
              }
            ],
            "url": {
              "raw": "{{base_url}}/api/orders/{{order_id}}",
              "host": ["{{base_url}}"],
              "path": ["api", "orders", "{{order_id}}"]
            }
          }
        }
      ]
    }
  ],
  "event": [
    {
      "listen": "prerequest",
      "script": {
        "type": "text/javascript",
        "exec": [
          "// Global pre-request script",
          "// Check if authentication token is valid",
          "const token = pm.environment.get('auth_token');",
          "const expiresAt = pm.environment.get('token_expires_at');",
          "",
          "// Auto-refresh token if needed",
          "if (token && expiresAt && Date.now() > parseInt(expiresAt)) {",
          "    console.log('Token expired, attempting refresh');",
          "    // This would trigger the refresh token request",
          "}",
          "",
          "// Set random values for dynamic data",
          "pm.environment.set('randomInt', Math.floor(Math.random() * 1000));",
          "pm.environment.set('randomPrice', (Math.random() * 100 + 10).toFixed(2));",
          "pm.environment.set('randomStock', Math.floor(Math.random() * 100) + 1);"
        ]
      }
    },
    {
      "listen": "test",
      "script": {
        "type": "text/javascript",
        "exec": [
          "// Global test script",
          "// Log response details for debugging",
          "console.log('Response Status:', pm.response.code);",
          "console.log('Response Time:', pm.response.responseTime);",
          "",
          "// Check if response time is acceptable",
          "pm.test('Response time is less than 3000ms', function () {",
          "    pm.expect(pm.response.responseTime).to.be.below(3000);",
          "});",
          "",
          "// Check content-type header",
          "pm.test('Response has Content-Type header', function () {",
          "    pm.expect(pm.response.headers.get('Content-Type')).to.include('application/json');",
          "});"
        ]
      }
    }
  ],
  "variable": [
    {
      "key": "randomUserName",
      "value": "{{$randomUserName}}"
    },
    {
      "key": "randomEmail",
      "value": "{{$randomEmail}}"
    },
    {
      "key": "randomPassword",
      "value": "{{$randomPassword}}"
    },
    {
      "key": "randomFirstName",
      "value": "{{$randomFirstName}}"
    },
    {
      "key": "randomLastName",
      "value": "{{$randomLastName}}"
    }
  ]
}
QuellcodejsonKomplex

Fortgeschrittene Postman Automatisierung und Tests

Erweiterte Postman Funktionen inklusive datengesteuerter Tests, Mock Server, Monitore und CI/CD Integration

Schwierigkeit

8/10

Geschätzte Zeit

50 min

Schlagwörter

postman, automation, performance, security, data-driven

Voraussetzungen

Postman basics, JavaScript, API testing concepts, CI/CD concepts

json
{
  "info": {
    "name": "Advanced API Testing Suite",
    "description": "Advanced collection with data-driven testing, performance monitoring, and automation features",
    "version": "2.0.0",
    "schema": "https://schema.getpostman.com/json/collection/v2.1.0/collection.json"
  },
  "item": [
    {
      "name": "Data-Driven Tests",
      "item": [
        {
          "name": "User Registration Data-Driven",
          "event": [
            {
              "listen": "prerequest",
              "script": {
                "exec": [
                  "// Load test data from CSV or environment",
                  "const testData = pm.collectionVariables.get('test_data') || [",
                  "  {username: 'testuser1', email: '[email protected]', password: 'password123', expectedStatus: 201},",
                  "  {username: 'testuser2', email: '[email protected]', password: 'password456', expectedStatus: 201},",
                  "  {username: '', email: '[email protected]', password: 'password789', expectedStatus: 400},",
                  "  {username: 'testuser3', email: 'invalid-email', password: 'password012', expectedStatus: 400}",
                  "];",
                  "",
                  "// Get current iteration data",
                  "const currentIndex = parseInt(pm.environment.get('data_iteration') || '0');",
                  "const currentData = testData[currentIndex % testData.length];",
                  "",
                  "// Set request body with current data",
                  "pm.environment.set('current_username', currentData.username);",
                  "pm.environment.set('current_email', currentData.email);",
                  "pm.environment.set('current_password', currentData.password);",
                  "pm.environment.set('expected_status', currentData.expectedStatus);",
                  "",
                  "// Increment iteration for next run",
                  "pm.environment.set('data_iteration', (currentIndex + 1).toString());"
                ],
                "type": "text/javascript"
              }
            },
            {
              "listen": "test",
              "script": {
                "exec": [
                  "const expectedStatus = parseInt(pm.environment.get('expected_status'));",
                  "",
                  "pm.test('Status code is ' + expectedStatus, function () {",
                  "    pm.response.to.have.status(expectedStatus);",
                  "});",
                  "",
                  "// Additional tests based on expected status",
                  "if (expectedStatus === 201) {",
                  "    pm.test('User created successfully', function () {",
                  "        const jsonData = pm.response.json();",
                  "        pm.expect(jsonData).to.have.property('user');",
                  "        pm.expect(jsonData.user.email).to.eql(pm.environment.get('current_email'));",
                  "    });",
                  "} else if (expectedStatus === 400) {",
                  "    pm.test('Validation error returned', function () {",
                  "        const jsonData = pm.response.json();",
                  "        pm.expect(jsonData).to.have.property('error');",
                  "    });",
                  "}"
                ],
                "type": "text/javascript"
              }
            }
          ],
          "request": {
            "method": "POST",
            "header": [
              {
                "key": "Content-Type",
                "value": "application/json"
              }
            ],
            "body": {
              "mode": "raw",
              "raw": "{\n  \"username\": \"{{current_username}}\",\n  \"email\": \"{{current_email}}\",\n  \"password\": \"{{current_password}}\",\n  \"firstName\": \"Test\",\n  \"lastName\": \"User\"\n}"
            },
            "url": {
              "raw": "{{base_url}}/api/auth/register",
              "host": ["{{base_url}}"],
              "path": ["api", "auth", "register"]
            }
          }
        }
      ]
    },
    {
      "name": "Performance Tests",
      "item": [
        {
          "name": "Load Test - Product Search",
          "event": [
            {
              "listen": "test",
              "script": {
                "exec": [
                  "// Performance assertions",
                  "pm.test('Response time is under 1000ms', function () {",
                  "    pm.expect(pm.response.responseTime).to.be.below(1000);",
                  "});",
                  "",
                  "pm.test('Response size is reasonable', function () {",
                  "    const responseSize = pm.response.responseSize;",
                  "    pm.expect(responseSize).to.be.below(1024 * 1024); // Less than 1MB",
                  "});",
                  "",
                  "// Log performance metrics",
                  "console.log('Performance Metrics:');",
                  "console.log('- Response Time:', pm.response.responseTime + 'ms');",
                  "console.log('- Response Size:', pm.response.responseSize + ' bytes');",
                  "console.log('- Headers Size:', pm.response.headers.length + ' headers');",
                  "",
                  "// Store performance data for analysis",
                  "const performanceData = {",
                  "    timestamp: new Date().toISOString(),",
                  "    responseTime: pm.response.responseTime,",
                  "    responseSize: pm.response.responseSize,",
                  "    statusCode: pm.response.code,",
                  "    endpoint: '/api/products/search'",
                  "    userAgent: pm.request.headers.get('User-Agent')",
                  "};",
                  "",
                  "// Send to monitoring service (pseudo-code)",
                  "// pm.sendRequest({",
                  "//     url: 'https://monitoring.example.com/api/metrics',",
                  "//     method: 'POST',",
                  "//     header: {",
                  "//         'Content-Type': 'application/json'",
                  "//     },",
                  "//     body: JSON.stringify(performanceData)",
                  "// });"
                ],
                "type": "text/javascript"
              }
            }
          ],
          "request": {
            "method": "GET",
            "header": [
              {
                "key": "Accept",
                "value": "application/json"
              }
            ],
            "url": {
              "raw": "{{base_url}}/api/products/search?q={{search_term}}&limit={{search_limit}}",
              "host": ["{{base_url}}"],
              "path": ["api", "products", "search"],
              "query": [
                {
                  "key": "q",
                  "value": "{{search_term}}",
                  "description": "Search query"
                },
                {
                  "key": "limit",
                  "value": "{{search_limit}}",
                  "description": "Number of results"
                }
              ]
            }
          }
        },
        {
          "name": "Stress Test - Concurrent Requests",
          "event": [
            {
              "listen": "prerequest",
              "script": {
                "exec": [
                  "// Simulate concurrent requests",
                  "const concurrentRequests = parseInt(pm.environment.get('concurrent_requests') || '5');",
                  "const requestDelay = Math.random() * 100; // Random delay up to 100ms",
                  "",
                  "console.log('Simulating concurrent request #' + (parseInt(pm.environment.get('request_count') || '0') + 1));",
                  "",
                  "// Add artificial delay to simulate real-world conditions",
                  "setTimeout(function() {",
                  "    pm.environment.set('request_count', (parseInt(pm.environment.get('request_count') || '0') + 1).toString());",
                  "}, requestDelay);"
                ],
                "type": "text/javascript"
              }
            },
            {
              "listen": "test",
              "script": {
                "exec": [
                  "// Stress test assertions",
                  "pm.test('Server responds under load', function () {",
                  "    // Allow 500 status under load",
                  "    pm.expect([200, 500]).to.include(pm.response.code);",
                  "});",
                  "",
                  "pm.test('Response time is acceptable under load', function () {",
                  "    // More lenient timeout under load",
                  "    pm.expect(pm.response.responseTime).to.be.below(5000);",
                  "});",
                  "",
                  "// Track request counts",
                  "const totalRequests = parseInt(pm.environment.get('total_requests') || '0') + 1;",
                  "pm.environment.set('total_requests', totalRequests.toString());",
                  "",
                  "const successCount = parseInt(pm.environment.get('success_count') || '0');",
                  "if (pm.response.code === 200) {",
                  "    pm.environment.set('success_count', (successCount + 1).toString());",
                  "}",
                  "",
                  "console.log('Total requests:', totalRequests);",
                  "console.log('Success rate:', (successCount / totalRequests * 100).toFixed(2) + '%');"
                ],
                "type": "text/javascript"
              }
            }
          ],
          "request": {
            "method": "GET",
            "url": {
              "raw": "{{base_url}}/api/health",
              "host": ["{{base_url}}"],
              "path": ["api", "health"]
            }
          }
        }
      ]
    },
    {
      "name": "Security Tests",
      "item": [
        {
          "name": "SQL Injection Test",
          "event": [
            {
              "listen": "test",
              "script": {
                "exec": [
                  "// Security test for SQL injection",
                  "const maliciousPayloads = [",
                  "    "'; DROP TABLE users; --",",
                  "    "' OR '1'='1",",
                  "    "'; INSERT INTO users (email) VALUES ('[email protected]'); --"",
                  "];",
                  "",
                  "pm.test('Server rejects SQL injection attempts', function () {",
                  "    // Should not return 200 for malicious payloads",
                  "    pm.expect(pm.response.code).to.not.eql(200);",
                  "});",
                  "",
                  "pm.test('No database error messages exposed', function () {",
                  "    const responseText = pm.response.text();",
                  "    const errorPatterns = [/SQL/i, /mysql/i, /database/i, /syntax error/i];",
                  "    ",
                  "    errorPatterns.forEach(pattern => {",
                  "        pm.expect(responseText).to.not.match(pattern);",
                  "    });",
                  "});",
                  "",
                  "pm.test('Response time is consistent', function () {",
                  "    // SQL injection should be rejected quickly",
                  "    pm.expect(pm.response.responseTime).to.be.below(1000);",
                  "});"
                ],
                "type": "text/javascript"
              }
            }
          ],
          "request": {
            "method": "POST",
            "header": [
              {
                "key": "Content-Type",
                "value": "application/json"
              }
            ],
            "body": {
              "mode": "raw",
              "raw": "{\n  \"email\": \"'; DROP TABLE users; --\",\n  \"password\": \"password123\"\n}"
            },
            "url": {
              "raw": "{{base_url}}/api/auth/login",
              "host": ["{{base_url}}"],
              "path": ["api", "auth", "login"]
            }
          }
        },
        {
          "name": "XSS Protection Test",
          "event": [
            {
              "listen": "test",
              "script": {
                "exec": [
                  "// XSS protection test",
                  "const xssPayloads = [",
                  "    '<script>alert("XSS")</script>',",
                  "    'javascript:alert("XSS")',",
                  "    '<img src="x" onerror="alert(\"XSS\")">',",
                  "    '"><script>alert("XSS")</script>'",
                  "];",
                  "",
                  "pm.test('Server sanitizes XSS attempts', function () {",
                  "    const responseText = pm.response.text();",
                  "    ",
                  "    // Check that script tags are removed or escaped",
                  "    pm.expect(responseText).to.not.include('<script>');",
                  "    pm.expect(responseText).to.not.include('javascript:');",
                  "    pm.expect(responseText).to.not.include('onerror=');",
                  "});",
                  "",
                  "pm.test('Response is safe for display', function () {",
                  "    const responseText = pm.response.text();",
                  "    ",
                  "    // No unescaped HTML or JavaScript",
                  "    const dangerousPatterns = [",
                  "        /<script/i,",
                  "        /javascript:/i,",
                  "        /on\w+=/i",
                  "    ];",
                  "    ",
                  "    dangerousPatterns.forEach(pattern => {",
                  "        pm.expect(responseText).to.not.match(pattern);",
                  "    });",
                  "});"
                ],
                "type": "text/javascript"
              }
            }
          ],
          "request": {
            "method": "POST",
            "header": [
              {
                "key": "Content-Type",
                "value": "application/json"
              }
            ],
            "body": {
              "mode": "raw",
              "raw": "{\n  \"name\": \"Test Product <script>alert('XSS')</script>\",\n  \"description\": \"<img src=\\\"x\\\" onerror=\\\"alert('XSS')\\\">\",\n  \"price\": 29.99\n}"
            },
            "url": {
              "raw": "{{base_url}}/api/products",
              "host": ["{{base_url}}"],
              "path": ["api", "products"]
            }
          }
        }
      ]
    },
    {
      "name": "API Documentation Tests",
      "item": [
        {
          "name": "OpenAPI Schema Validation",
          "event": [
            {
              "listen": "test",
              "script": {
                "exec": [
                  "// Validate response against OpenAPI schema",
                  "const validateAgainstSchema = function(response, schemaName) {",
                  "    try {",
                  "        const responseJson = response.json();",
                  "        // This would integrate with OpenAPI validation library",
                  "        // For now, we'll do basic structural validation",
                  "        ",
                  "        const schemas = {",
                  "            'User': ['id', 'username', 'email'],",
                  "            'Product': ['id', 'name', 'price', 'description'],",
                  "            'Order': ['id', 'userId', 'items', 'totalAmount', 'status']",
                  "        };",
                  "        ",
                  "        const requiredFields = schemas[schemaName] || [];",
                  "        ",
                  "        requiredFields.forEach(field => {",
                  "            pm.expect(responseJson).to.have.property(field);",
                  "        });",
                  "        ",
                  "        return true;",
                  "    } catch (error) {",
                  "        console.log('Schema validation error:', error.message);",
                  "        return false;",
                  "    }",
                  "};",
                  "",
                  "pm.test('Response matches OpenAPI schema', function () {",
                  "    const endpoint = pm.info.requestName;",
                  "    let schemaName = 'Unknown';",
                  "    ",
                  "    if (endpoint.includes('User')) schemaName = 'User';",
                  "    else if (endpoint.includes('Product')) schemaName = 'Product';",
                  "    else if (endpoint.includes('Order')) schemaName = 'Order';",
                  "    ",
                  "    const isValid = validateAgainstSchema(pm.response, schemaName);",
                  "    pm.expect(isValid).to.be.true;",
                  "});",
                  "",
                  "// Test response headers for API compliance",
                  "pm.test('API compliance headers present', function () {",
                  "    pm.expect(pm.response.headers.get('X-API-Version')).to.exist;",
                  "    pm.expect(pm.response.headers.get('X-Rate-Limit-Remaining')).to.exist;",
                  "    pm.expect(pm.response.headers.get('Cache-Control')).to.exist;",
                  "});"
                ],
                "type": "text/javascript"
              }
            }
          ],
          "request": {
            "method": "GET",
            "header": [
              {
                "key": "Accept",
                "value": "application/json"
              }
            ],
            "url": {
              "raw": "{{base_url}}/api/products/{{product_id}}",
              "host": ["{{base_url}}"],
              "path": ["api", "products", "{{product_id}}"]
            }
          }
        }
      ]
    }
  ],
  "event": [
    {
      "listen": "prerequest",
      "script": {
        "exec": [
          "// Global advanced pre-request script",
          "// Load environment-specific configurations",
          "const environment = pm.environment.get('env_type') || 'development';",
          "const configs = {",
          "    development: {",
          "        timeout: 5000,",
          "        retries: 1,",
          "        strict_ssl: false",
          "    },",
          "    staging: {",
          "        timeout: 3000,",
          "        retries: 2,",
          "        strict_ssl: true",
          "    },",
          "    production: {",
          "        timeout: 2000,",
          "        retries: 3,",
          "        strict_ssl: true",
          "    }",
          "};",
          "",
          "const config = configs[environment];",
          "pm.environment.set('request_timeout', config.timeout.toString());",
          "pm.environment.set('max_retries', config.retries.toString());",
          "",
          "// Advanced error tracking",
          "pm.environment.set('request_start_time', Date.now().toString());",
          "pm.environment.set('request_uuid', pm.variables.replaceIn('{{$randomUUID}}'));"
        ],
        "type": "text/javascript"
      }
    },
    {
      "listen": "test",
      "script": {
        "exec": [
          "// Global advanced test script",
          "// Comprehensive logging and monitoring",
          "const requestStartTime = parseInt(pm.environment.get('request_start_time') || Date.now());",
          "const requestUuid = pm.environment.get('request_uuid');",
          "const responseTime = Date.now() - requestStartTime;",
          "",
          "// Advanced logging with correlation ID",
          "console.log('=== Request Details ===');",
          "console.log('Request ID:', requestUuid);",
          "console.log('Method:', pm.info.requestMethod);",
          "console.log('URL:', pm.info.requestName);",
          "console.log('Status Code:', pm.response.code);",
          "console.log('Response Time:', responseTime + 'ms');",
          "console.log('Response Size:', pm.response.responseSize + ' bytes');",
          "console.log('Environment:', pm.environment.get('env_type'));",
          "console.log('========================');",
          "",
          "// Performance thresholds based on environment",
          "const envType = pm.environment.get('env_type') || 'development';",
          "const thresholds = {",
          "    development: 5000,",
          "    staging: 3000,",
          "    production: 2000",
          "};",
          "",
          "const threshold = thresholds[envType];",
          "",
                  "pm.test('Response time meets SLA (' + threshold + 'ms)', function () {",
                  "    pm.expect(responseTime).to.be.below(threshold);",
                  "});",
                  "",
                  "// Advanced response validation",
                  "pm.test('Response structure is valid JSON', function () {",
                  "    try {",
                  "        const responseJson = pm.response.json();",
                  "        pm.expect(responseJson).to.be.an('object');",
                  "    } catch (e) {",
                  "        // If response is not JSON, that's okay for some endpoints",
                  "        if (pm.response.headers.get('Content-Type')?.includes('application/json')) {",
                  "            throw e;",
                  "        }",
                  "    }",
                  "});",
                  "",
                  "// Error handling and alerting",
                  "if (pm.response.code >= 500) {",
                  "    console.error('SERVER ERROR DETECTED!');",
                  "    console.error('Request ID:', requestUuid);",
                  "    console.error('Response:', pm.response.text());",
                  "    ",
                  "    // Send alert to monitoring system (pseudo-code)",
                  "    // sendAlert({",
                  "    //     level: 'error',",
                  "    //     message: 'Server error in API call',",
                  "    //     requestId: requestUuid,",
                  "    //     endpoint: pm.info.requestName,",
                  "    //     statusCode: pm.response.code",
                  "    // });",
                  "}",
                  "",
                  "// Track test execution metrics",
                  "const testMetrics = {",
                  "    timestamp: new Date().toISOString(),",
                  "    requestId: requestUuid,",
                  "    endpoint: pm.info.requestName,",
                  "    method: pm.info.requestMethod,",
                  "    statusCode: pm.response.code,",
                  "    responseTime: responseTime,",
                  "    responseSize: pm.response.responseSize,",
                  "    environment: envType",
                  "};",
                  "",
                  "// Store metrics for analysis",
                  "const metricsArray = JSON.parse(pm.environment.get('test_metrics') || '[]');",
                  "metricsArray.push(testMetrics);",
                  "",
                  "// Keep only last 100 metrics to avoid memory issues",
                  "if (metricsArray.length > 100) {",
                  "    metricsArray.splice(0, metricsArray.length - 100);",
                  "}",
                  "",
                  "pm.environment.set('test_metrics', JSON.stringify(metricsArray));"
        ],
        "type": "text/javascript"
      }
    }
  ],
  "variable": [
    {
      "key": "data_iteration",
      "value": "0"
    },
    {
      "key": "concurrent_requests",
      "value": "5"
    },
    {
      "key": "request_count",
      "value": "0"
    },
    {
      "key": "total_requests",
      "value": "0"
    },
    {
      "key": "success_count",
      "value": "0"
    },
    {
      "key": "test_metrics",
      "value": "[]"
    }
  ]
}

// Environment Configuration Examples:

// Development Environment:
/*
{
  "name": "Development",
  "values": [
    {
      "key": "base_url",
      "value": "http://localhost:3000",
      "enabled": true
    },
    {
      "key": "admin_email",
      "value": "[email protected]",
      "enabled": true
    },
    {
      "key": "admin_password",
      "value": "password123",
      "enabled": true
    },
    {
      "key": "page",
      "value": "1",
      "enabled": true
    },
    {
      "key": "limit",
      "value": "10",
      "enabled": true
    },
    {
      "key": "search_term",
      "value": "laptop",
      "enabled": true
    },
    {
      "key": "search_limit",
      "value": "20",
      "enabled": true
    },
    {
      "key": "env_type",
      "value": "development",
      "enabled": true
    }
  ]
}
*/

// Newman Command Line Usage:
/*
// Run collection with environment
newman run collection.json -e environment.json

// Run with data file for data-driven testing
newman run collection.json -d test_data.csv

// Generate reports
newman run collection.json -r html,cli,json

// Run specific folders
newman run collection.json --folder "Authentication"

// Run with iteration count
newman run collection.json -n 5

// Run with timeout
newman run collection.json --timeout-request 10000

// Ignore redirects
newman run collection.json --ignore-redirects

// Run with global variables
newman run collection.json --global-var "base_url=https://api.example.com"
*/

// CSV Example for Data-Driven Testing:
/*
username,email,password,expectedStatus
testuser1,[email protected],password123,201
testuser2,[email protected],password456,201
invalid,[email protected],password789,400
,[email protected],password012,400
*/

Werkzeuge

Tools, die oft mit diesem Beispiel genutzt werden

Verwandt

Verwandte Beispielsammlungen

Verwandt

Verwandte Themen

Leitfaden zur Tool-Nutzung

Kontext zum Verständnis dieser Beispielsammlung

Titel

Postman Collections - API Tests

Beschreibung

Umfassende Postman Collection Beispiele inklusive API Tests, Automatisierungsskripte, Umgebungsvariablen, Mock Server und fortgeschrittene Testmuster für REST APIs

Überblick

Umfassende Postman Collection Beispiele inklusive API Tests, Automatisierungsskripte, Umgebungsvariablen, Mock Server und fortgeschrittene Testmuster für REST APIs

Wann verwenden

  • Use this sample set when you want reference inputs for Postman Collections - API Tests.
  • Use it to preview output formats and compare related sample variants.

So funktioniert es

  1. 1Open a sample entry to inspect the prepared example payload or asset.
  2. 2Compare it with related tools to understand how the workflow connects.

Anwendungsfälle

  • Postman Basis Collection Setup
  • Fortgeschrittene Postman Automatisierung und Tests

FAQ

What is included in Postman Collections - API Tests?

This page includes curated sample entries, related tools, and neighboring sample collections for Postman Collections - API Tests.

Thema

OpenAPI Utility Workflow

Erzeuge OpenAPI-Typen und Doku, pruefe Breaking Changes, validiere Responses und haerte den Vertrag mit Stress- und Mutationstests.

Thema

JSON-Schema- und API-Vertragsvalidierungs-Tools

Vergleichen Sie JSON-Schema-Validierung, OpenAPI-Response-Prüfung, Mutation Testing, Stress Testing und Breaking-Change-Erkennung in einem Hub für API-Vertragsreviews.

Thema

API-Verträge definieren, Schemas validieren und Änderungen testen

Definieren Sie einen API-Vertrag, prüfen Sie Schemas und aufgezeichnete Payloads, erkennen Sie Kompatibilitätsrisiken und dokumentieren Sie die Abnahme.

Thema

Audio-Metadaten, Tags, Kapitel und Cover

Bereiten Sie Musik- oder Podcast-Dateien mit geprüften Tags, Covern, Kapiteln und sauberen Liefermetadaten vor.

Start
Werkzeuge3201
Beispiele593
Visualisierungen465
Dateibetrachter103
Themen233
Schlagwörter333
Bilder, Audio & Video657

Werkzeuge für Bild-, Audio- und Videobearbeitung, Konvertierung und Optimierung

Mathe, Datum & Finanzen644

Rechner, Zahlenwerkzeuge, Datumslogik, Statistik und Finanztools

Design & Farbe297

Werkzeuge für Farben, Layouts, Grafiken, visuelle Gestaltung und Designhilfen

Text & Schreiben209

Werkzeuge für Schreiben, Bereinigung, Formatierung, Extraktion und Textanalyse

Entwicklung & Web193

Entwicklerwerkzeuge, Netzwerk-Utilities, Web-Debugging und Automatisierungshelfer

Konvertierung & Kodierung175

Werkzeuge für Format-, Datei-, Archiv-, Einheiten- und Kodierungskonvertierung

FLAC/WAV-Quellen prüfen und Nachweise übergeben
Selbst gehostetes Gewinnspiel-Widget prüfen und zur Einbettung übergeben
Stripe-Codepaket prüfen und lokalen Import vorbereiten
Technische Fotoauswahl prüfen und Kandidaten zur Bearbeitung übergeben
UI-Screenshot strukturieren, prüfen und an die Entwicklung übergeben

© 2026 Elysia Tools. Alle Rechte vorbehalten.

DokumentationTarifeÜber unsNutzungsbedingungenDatenschutzerklärungCookiesKontakt

Development

API Mock Server

Erzeugt einen temporaeren Redis-basierten Mock-Server mit dynamischen Antworten

Format Conversion

XLSX API zu Sheet

Schreibt REST/GraphQL JSON in ein Excel-Blatt

Development

API-Latenzbudget-Planer

Planen und visualisieren Sie ein API-Latenzbudget. Geben Sie ein P99-Ziel (z. B. ≤ 300ms) und die Phasenzuweisung (DNS, TCP, TLS, TTFB, Processing, Network) ein, um ein Live-Waterfall, die Budgetauslastung und Warnungen bei Überschreitung zu sehen. Optional OpenTelemetry- oder Datadog-Trace einfügen, um eine gemessene Zuweisung abzuleiten.

Development

API-Request-Code-Snippet-Generator

Erzeugt cURL- und gaengige Sprach-Snippets aus URL, Methode, Headern, Query-Parametern und Body

Development

API-Response-Contract-Validator

Validiert eine echte API-Antwort gegen das in OpenAPI 3.x deklarierte Response-Schema

Development

API-Response-Diff-und-Semantik-Analyzer

Vergleicht zwei API-Antworten und trennt funktionale Aenderungen von harmlosen Laufzeitdifferenzen

Development

OpenAPI zu Postman Collection

Wandelt eine OpenAPI-3.x- oder Swagger-2.0-Spec (JSON/YAML) in eine importierbare Postman Collection v2.1.0 mit Ordnern, Variablen, Auth und Beispielantworten.

Development

JSON-Diff-Visualisierung

Vergleicht zwei JSON-Dokumente und erzeugt einen visuellen Bericht mit Pfaden und Statistik

DevOps

ELK Stack Log-Analyse Beispiele

Umfassende ELK Stack Beispiele für Log-Aggregation, -Verarbeitung und -Visualisierung in verteilten Systemen

Entwicklung

Terraform-Plan-JSON-Beispiele

Terraform-Plan-JSON-Dateien fuer Abhaengigkeitsvisualisierung und Change-Review, passend zu terraform show -json

API-Dokumentation

OpenAPI/Swagger Beispiele

Umfassende API-Dokumentationsbeispiele mit OpenAPI 3.0 und Swagger-Spezifikationen für RESTful-Services

Observability

Distributed Tracing Beispiele

Umfassende Beispiele für verteiltes Tracing mit Jaeger, OpenTelemetry und modernen Observability Tools

Cloud-Dienste

AWS EventBridge Beispiele

AWS EventBridge Beispiele einschließlich Event Buses, Rules, Targets, Schema Registry, Custom Events und Cross-Account Event Routing für Serverless Event-Driven Architecture

Überwachung

Grafana Fortgeschrittene Anwendungsbeispiele

Umfassende Grafana-Beispiele für fortgeschrittenes Dashboard-Design, Alerting-Konfiguration, Datenquellen-Integration und Plugin-Entwicklung