Post

API Testing

API Testing

Pengenalan

Dalam era aplikasi modern yang berbasis microservices dan cloud, API (Application Programming Interface) telah menjadi jantung dari komunikasi antar sistem. API Testing adalah teknik pengujian yang memastikan API berfungsi dengan baik, reliable, secure, dan performa optimal.


Definisi API Testing

Apa itu API Testing?

API Testing adalah jenis pengujian perangkat lunak yang fokus pada menguji Application Programming Interface (API) secara langsung. Pengujian ini memverifikasi bahwa API berfungsi dengan baik, mengirimkan data yang benar, menghandle error dengan sempurna, dan memenuhi ekspektasi performance, security, dan reliability.

Definisi Formal:

1
2
3
API Testing adalah proses pengujian teknis yang memeriksa fungsionalitas,
keandalan, performa, dan keamanan dari Application Programming Interface
tanpa melibatkan User Interface (UI) secara langsung.

Karakteristik API Testing

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
✅ No UI Required
   └─ Test API secara langsung tanpa GUI
   └─ Faster & more reliable than UI testing

✅ Focus on Business Logic
   └─ Test core functionality
   └─ Independent dari presentasi layer

✅ Data-Driven
   └─ Request & Response berupa data (JSON, XML, etc)
   └─ Easy to validate & parse

✅ Automation-Friendly
   └─ Mudah diotomasi dengan script
   └─ Integrasi dengan CI/CD pipeline

✅ Early Testing
   └─ Dapat dilakukan sebelum UI selesai
   └─ Parallel development possible

✅ Comprehensive Coverage
   └─ Test semua HTTP methods
   └─ Test berbagai status codes
   └─ Test error handling

✅ Language-Agnostic
   └─ Tidak tergantung teknologi implementasi
   └─ API sama untuk semua client

Scope API Testing

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
TESTING PYRAMID - API Testing Layer
═════════════════════════════════════════════════════════════

            / \
           /E2E\          E2E/UI Testing (10%)
          /─────\         ──────────────────
         /       \        
        /   API   \       API/Integration Testing (50%)
       /───────────\      ──────────────────
      /             \      
     /     Unit      \    Unit Testing (40%)
    /─────────────────\   ──────────────────
   ╰───────────────────╯

API TESTING FOKUS:
  ├─ API endpoints functionality
  ├─ HTTP methods (GET, POST, PUT, DELETE, PATCH)
  ├─ Request parameters (path, query, body)
  ├─ Response status codes & headers
  ├─ Response body & data format
  ├─ Error handling & validation
  ├─ Authentication & authorization
  ├─ Rate limiting & throttling
  └─ Performance & load testing

TIDAK termasuk:
  ├─ UI testing
  ├─ Browser compatibility
  ├─ Visual rendering
  └─ Frontend interactions

Keunggulan API Testing

Mengapa API Testing itu Penting?

1. 🚀 Early Detection of Issues

1
2
3
4
5
6
7
8
9
10
11
12
13
14
API Testing dapat dilakukan SEBELUM UI selesai

Timeline:
  Day 1-5:     Backend development
  Day 5:       ✓ API Testing dimulai (sambil UI dikerjakan)
  Day 10-15:   Frontend development
  Day 15:      UI Testing
  Day 20:      Integration Testing

MANFAAT:
  ✓ Bugs ditemukan lebih awal
  ✓ Paralel development possible
  ✓ Faster time to market
  ✓ Reduced cost

2. 💪 Core Functionality Verification

1
2
3
4
5
6
7
8
9
10
11
12
13
API adalah jantung dari aplikasi

API Testing memverifikasi:
  ✓ Business logic bekerja dengan benar
  ✓ Data processed correctly
  ✓ Database transactions valid
  ✓ Business rules enforced
  
Contoh (BMI Calculator API):
  GET  /api/bmi/history        → Retrieve history
  POST /api/bmi/calculate      → Calculate BMI
  PUT  /api/bmi/{id}           → Update entry
  DELETE /api/bmi/{id}         → Delete entry

3. 🔒 Security Verification

1
2
3
4
5
6
7
8
9
10
11
12
13
14
API Testing dapat mengidentifikasi security issues:

  ✓ Unauthorized access prevention
  ✓ Authentication & authorization
  ✓ SQL injection prevention
  ✓ Data exposure prevention
  ✓ API rate limiting
  ✓ Invalid input handling
  
Contoh:
  Test dengan SQL injection: ' OR '1'='1
  Test dengan invalid token
  Test dengan expired credentials
  Test dengan missing required fields

4. ⚡ Performance Testing

1
2
3
4
5
6
7
8
9
10
11
12
API Testing dapat mengukur performa:

  ✓ Response time < target (e.g., <200ms)
  ✓ Throughput (requests/second)
  ✓ Load handling
  ✓ Concurrent users support
  ✓ Resource utilization
  
Contoh:
  Single request: 150ms ✓
  1000 concurrent: 300ms ✓
  10000 requests/min: ✓

5. 🔄 Regression Prevention

1
2
3
4
5
6
7
8
9
10
11
12
Setiap kali code berubah:

  ✓ API tests memastikan tidak ada break
  ✓ Existing functionality preserved
  ✓ Backward compatibility maintained
  ✓ Side effects detected

Confidence untuk:
  ✓ Deploy frequently
  ✓ Refactor dengan aman
  ✓ Update dependencies
  ✓ Scale infrastructure

6. 📚 Living Documentation

1
2
3
4
5
6
7
8
9
10
11
12
API tests berfungsi sebagai dokumentasi:

  ✓ Clear examples of how to use API
  ✓ Request/response examples
  ✓ Error handling patterns
  ✓ Validation rules
  
Contoh dokumentasi dari test:
  POST /api/bmi/calculate
  Request: {"weight": 55, "height": 150}
  Response: {"bmi": 24.44, "classification": "Normal"}
  Errors: 400 for invalid input, 500 for server error

7. 💰 Cost Effective

1
2
3
4
5
6
7
8
9
10
11
12
API Testing ROI:

Cost comparison:
  Manual UI testing:    $1000/day
  Automated API test:   $100/setup + $10/run
  Ratio:                10x cheaper

Savings:
  ✓ Faster execution (1ms vs 1s per test)
  ✓ No manual intervention needed
  ✓ Reusable across projects
  ✓ Easy to maintain & update

Comparison: API Testing vs UI Testing

AspekUI TestingAPI Testing
Test ExecutionSlow (1-5s per test)Fast (<100ms per)
ReliabilityFlaky (element sync)Stable (consistent)
MaintenanceHigh (UI changes)Low (stable API)
CoverageLimited (happy path)Comprehensive
Start TimelineLate (UI needed)Early (just API)
AutomationMedium difficultyEasy to automate
CostHighLow
Browser CompatRequiredNot needed
Data ValidationLimitedComprehensive
Error TestingLimitedThorough
Performance DataLimitedDetailed metrics
Load TestingDifficultEasy

Tools untuk API Testing

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
Postman adalah tool paling populer untuk API testing

Versi: Postman v11 (latest)
Platform: Desktop (Windows, macOS, Linux) + Web
Creator: Postman Inc.

Fitur:
  ✓ User-friendly interface
  ✓ Request building & sending
  ✓ Response visualization
  ✓ Automated testing (Tests)
  ✓ Collections & Environments
  ✓ Pre-request scripts
  ✓ Authentication (Basic, Bearer, OAuth)
  ✓ Mocking servers
  ✓ Documentation generation
  ✓ Collaboration features
  ✓ API monitoring
  ✓ CI/CD integration (Newman CLI)

Keunggulan:
  ✓ Very beginner-friendly
  ✓ Rich feature set
  ✓ Large community
  ✓ Great documentation
  ✓ Free version available
  ✓ Cross-platform

Kekurangan:
  ✓ Can be slow with large datasets
  ✓ Learning curve for advanced features
  ✓ Premium features for team collaboration

Instalasi:
  1. Visit: https://www.postman.com/downloads/
  2. Download installer
  3. Run installer
  4. Create free account
  5. Start testing!

Pricing:
  ✓ Free tier: Good for individuals
  ✓ Team ($12/user/month): For teams
  ✓ Business ($25/user/month): For enterprises

2. SoapUI (Enterprise)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
SoapUI adalah tool yang powerful untuk SOAP & REST API testing

Version: SoapUI 5.7+ & SoapUI Pro
Platform: Java-based (cross-platform)
Creator: SmartBear

Fitur:
  ✓ SOAP & REST support
  ✓ Functional testing
  ✓ Performance/load testing
  ✓ Security testing
  ✓ Automation scripting
  ✓ Data-driven testing
  ✓ Mock services
  ✓ API mocking
  ✓ Advanced assertions
  ✓ Integration with tools

Keunggulan:
  ✓ Powerful for complex scenarios
  ✓ Built-in load testing
  ✓ Professional features
  ✓ SOAP protocol support
  ✓ Good for enterprises

Kekurangan:
  ✓ Steeper learning curve
  ✓ Heavier (Java-based)
  ✓ Expensive licensing
  ✓ Less beginner-friendly

Instalasi:
  1. Visit: https://www.soapui.org/
  2. Download SoapUI open source or Pro
  3. Install
  4. Create project & start testing

3. Thunder Client (VS Code Extension)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
Thunder Client adalah lightweight alternative untuk Postman

Platform: VS Code extension
Creator: Thunder Client team

Fitur:
  ✓ Simple UI
  ✓ REST API testing
  ✓ Collections
  ✓ Environments
  ✓ Authorization
  ✓ Built-in tests
  ✓ Code generation

Keunggulan:
  ✓ Lightweight
  ✓ Integrated in VS Code
  ✓ Simple & fast
  ✓ Free

Kekurangan:
  ✓ Less mature than Postman
  ✓ Smaller feature set
  ✓ Smaller community

Instalasi:
  1. Open VS Code
  2. Extensions marketplace
  3. Search "Thunder Client"
  4. Click Install

4. Insomnia (Developer-Friendly)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
Insomnia adalah REST client yang elegant

Version: Insomnia v2023+
Platform: Desktop (Windows, macOS, Linux)
Creator: Kong

Fitur:
  ✓ Clean interface
  ✓ Request building
  ✓ Response visualization
  ✓ Environment variables
  ✓ Authentication
  ✓ Testing
  ✓ Request chaining
  ✓ Plugin system

Keunggulan:
  ✓ Beautiful UI
  ✓ Developer-friendly
  ✓ Fast & responsive
  ✓ Open-source option

Kekurangan:
  ✓ Smaller community than Postman
  ✓ Fewer advanced features
  ✓ Limited collaboration tools

Instalasi:
  https://insomnia.rest/download

Tools Comparison

FiturPostmanSoapUIThunderInsomnia
REST API✓✓✓✓✓✓✓✓✓✓✓
SOAPLimited✓✓✓
Ease of Use✓✓✓✓✓✓✓✓✓
Performance Testing✓✓✓
Security Testing✓✓✓
Automation✓✓✓✓✓✓✓
Collections✓✓✓✓✓✓✓✓✓
Environments✓✓✓✓✓✓✓✓✓
CI/CD Integration✓✓✓✓✓✓
Learning CurveEasyHardEasyEasy
Community✓✓✓✓✓✓✓
Free Version
PricingAffordableExpensiveFreeFreemium

RECOMMENDATION:

  • For beginners & general use: Postman
  • For SOAP + REST: SoapUI
  • For VS Code users: Thunder Client
  • For beautiful UI: Insomnia

Konsep Dasar API

Apa itu API?

API (Application Programming Interface) adalah set of protocols, tools, dan definitions yang memungkinkan software applications untuk berkomunikasi satu sama lain.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
API ANALOGY
═════════════════════════════════════════════════════════════

Bayangkan restaurant:

  ┌─────────────────────────────────────────┐
  │ RESTAURANT (Backend/Server)             │
  │                                         │
  │ ┌─────────────────────────────────────┐ │
  │ │ Kitchen (Business Logic)            │ │
  │ │ - Prepare dishes                    │ │
  │ │ - Cook food                         │ │
  │ └─────────────────────────────────────┘ │
  └─────────────────────────────────────────┘
                      ▲
                      │ API (Menu)
                      │
  ┌─────────────────────────────────────────┐
  │ CUSTOMER (Client/Frontend)              │
  │                                         │
  │ - Read menu                             │
  │ - Place order (Request)                 │
  │ - Receive food (Response)               │
  └─────────────────────────────────────────┘

Menu (API) adalah interface antara customer & kitchen
Menu defines:
  ✓ Available dishes (endpoints)
  ✓ Ingredients (parameters)
  ✓ How to order (HTTP methods)
  ✓ Delivery time (response time)

REST API

REST (Representational State Transfer) adalah architectural style paling populer untuk API.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
REST PRINCIPLES
═════════════════════════════════════════════════════════════

1. Client-Server Architecture
   ├─ Client (consumer)
   └─ Server (provider)

2. Stateless Communication
   ├─ Setiap request standalone
   └─ Server tidak menyimpan client context

3. Uniform Interface
   ├─ Standard way to access resources
   ├─ Resources identified by URIs
   └─ Resources manipulated via HTTP methods

4. Resource-Based URLs
   ├─ /api/users (resource: users)
   ├─ /api/users/123 (specific user)
   ├─ /api/users/123/posts (nested resource)

5. HTTP Methods (Verbs)
   ├─ GET:    Retrieve resource
   ├─ POST:   Create new resource
   ├─ PUT:    Replace entire resource
   ├─ PATCH:  Partial update
   ├─ DELETE: Remove resource
   ├─ HEAD:   Like GET but no body
   └─ OPTIONS: Describe communication options

6. Status Codes
   ├─ 2xx: Success
   ├─ 3xx: Redirection
   ├─ 4xx: Client error
   └─ 5xx: Server error

7. Content Negotiation
   ├─ JSON (most common)
   ├─ XML
   ├─ CSV
   └─ Others

HTTP Status Codes

CodeMeaning & Usage
200OK - Request succeeded
201Created - Resource created successfully
204No Content - Success but no content to return
400Bad Request - Client error (invalid syntax)
401Unauthorized - Authentication required
403Forbidden - Authenticated but not authorized
404Not Found - Resource doesn’t exist
409Conflict - Request conflicts with current state
422Unprocessable Entity - Validation failed
500Internal Server Error - Server error
502Bad Gateway - Invalid response from server
503Service Unavailable - Server temporarily down
429Too Many Requests - Rate limit exceeded
503Service Unavailable - Server is down

Anatomi Request & Response

Request Structure

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
HTTP REQUEST STRUCTURE
═════════════════════════════════════════════════════════════

┌──────────────────────────────────────────────────────────┐
│ REQUEST LINE (Method + URL + HTTP Version)               │
│ ──────────────────────────────────────────────────────   │
│ POST /api/bmi/calculate HTTP/1.1                         │
└──────────────────────────────────────────────────────────┘

┌──────────────────────────────────────────────────────────┐
│ HEADERS (Metadata tentang request)                       │
│ ──────────────────────────────────────────────────────   │
│ Host: api.example.com                                    │
│ Content-Type: application/json                           │
│ Authorization: Bearer eyJhbGc...                         │
│ User-Agent: PostmanRuntime/7.32.3                        │
│ Accept: application/json                                 │
│ Content-Length: 42                                       │
└──────────────────────────────────────────────────────────┘

┌──────────────────────────────────────────────────────────┐
│ EMPTY LINE (Separator)                                   │
└──────────────────────────────────────────────────────────┘

┌──────────────────────────────────────────────────────────┐
│ REQUEST BODY (Data yang dikirim)                         │
│ ──────────────────────────────────────────────────────   │
│ {                                                        │
│   "weight": 55,                                          │
│   "height": 150                                          │
│ }                                                        │
└──────────────────────────────────────────────────────────┘

Response Structure

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
HTTP RESPONSE STRUCTURE
═════════════════════════════════════════════════════════════

┌──────────────────────────────────────────────────────────┐
│ STATUS LINE (HTTP Version + Status Code + Message)       │
│ ──────────────────────────────────────────────────────   │
│ HTTP/1.1 200 OK                                          │
└──────────────────────────────────────────────────────────┘

┌──────────────────────────────────────────────────────────┐
│ RESPONSE HEADERS (Metadata tentang response)             │
│ ──────────────────────────────────────────────────────   │
│ Content-Type: application/json                           │
│ Content-Length: 82                                       │
│ Server: nginx/1.21.0                                     │
│ Date: Thu, 30 Oct 2025 10:38:44 GMT                      │
│ X-RateLimit-Limit: 1000                                  │
│ X-RateLimit-Remaining: 999                               │
│ Cache-Control: no-cache, no-store, must-revalidate       │
└──────────────────────────────────────────────────────────┘

┌──────────────────────────────────────────────────────────┐
│ EMPTY LINE (Separator)                                   │
└──────────────────────────────────────────────────────────┘

┌──────────────────────────────────────────────────────────┐
│ RESPONSE BODY (Data yang dikembalikan)                   │
│ ──────────────────────────────────────────────────────   │
│ {                                                        │
│   "bmi": 24.44,                                          │
│   "classification": "Normal",                            │
│   "status": "success",                                   │
│   "timestamp": "2025-10-30T10:38:44Z"                    │
│ }                                                        │
└──────────────────────────────────────────────────────────┘

Request Components Detail

URL Structure

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
URL ANATOMY
═════════════════════════════════════════════════════════════

https://api.example.com:8080/api/v1/users/123?limit=10&sort=name

└─┬─┘   └──┬──────────┘└──┬──┘└──┬─┘└────┬────┘└──────┬─────────┘
  │         │             │      │       │            │
  │         │             │      │       │            └─ Query String
  │         │             │      │       │
  │         │             │      │       └─ Path (Resource + ID)
  │         │             │      │
  │         │             │      └─ API Version
  │         │             │
  │         │             └─ Base Path
  │         │
  │         └─ Domain/Host
  │
  └─ Protocol (http, https)

Components:
  ✓ Protocol: https (secure)
  ✓ Host: api.example.com
  ✓ Port: 8080 (optional)
  ✓ Path: /api/v1/users/123
  ✓ Query: ?limit=10&sort=name (optional)

Request Types

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
1. PATH PARAMETERS
   └─ Part of the URL path
   └─ Identify specific resource
   └─ Example: /api/bmi/{id}
   
   GET /api/bmi/123  ← 123 is path parameter

2. QUERY PARAMETERS
   └─ After ? in URL
   └─ Filter, sort, pagination
   └─ Multiple values allowed
   
   GET /api/bmi?limit=10&offset=20&sort=desc

3. REQUEST HEADERS
   └─ Metadata tentang request
   └─ Specify format, auth, etc
   
   Content-Type: application/json
   Authorization: Bearer token123

4. REQUEST BODY
   └─ Data dalam request
   └─ Usually POST/PUT/PATCH
   └─ JSON, XML, Form data
   
   POST /api/bmi
   {
     "weight": 55,
     "height": 150
   }

Operasi Dasar di Postman

1. Installation & Setup

1
2
3
4
5
6
7
8
9
10
11
12
13
# Step 1: Download
Visit: https://www.postman.com/downloads/

# Step 2: Install
Run installer (.exe, .dmg, or .AppImage)

# Step 3: Create Account
Open Postman → Create free account

# Step 4: Verify Installation
Open Postman → Sign in

Ready to test!

2. Creating First Request

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
STEP-BY-STEP: Create GET Request
═════════════════════════════════════════════════════════════

Step 1: Open Postman
  └─ Click "+" button to create new request

Step 2: Enter Request Details
  ├─ Method: GET (dropdown)
  ├─ URL: https://jsonplaceholder.typicode.com/posts/1
  └─ Click Send

Step 3: View Response
  ├─ Status: 200 OK (green)
  ├─ Response Body: JSON data
  ├─ Response Time: e.g., 245ms
  └─ Response Size: e.g., 1.2 KB

3. Setting Request Headers

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
Adding Headers in Postman
═════════════════════════════════════════════════════════════

Step 1: Click "Headers" tab below URL

Step 2: Add Headers (Key-Value pairs)
  │
  └─ Common Headers:
     ├─ Content-Type: application/json
     ├─ Authorization: Bearer token_here
     ├─ Accept: application/json
     ├─ User-Agent: MyApp/1.0
     └─ Custom-Header: value

Step 3: Send Request
  └─ Headers will be included in request

4. Sending Request Body

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
POST Request with Body
═════════════════════════════════════════════════════════════

Step 1: Set Method to POST
  └─ Click Method dropdown → Select POST

Step 2: Enter URL
  └─ https://jsonplaceholder.typicode.com/posts

Step 3: Click "Body" tab

Step 4: Select Body Type
  ├─ raw (JSON)  ← Most common
  ├─ form-data
  ├─ x-www-form-urlencoded
  └─ binary

Step 5: Enter JSON Data (for raw)
  └─ {
       "title": "My BMI",
       "body": "Testing API",
       "userId": 1
     }

Step 6: Send
  └─ Click Send button

5. Using Variables & Environment

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
Using Variables for Flexibility
═════════════════════════════════════════════════════════════

Step 1: Create Environment
  ├─ Top right → "No Environment"
  ├─ Click dropdown → "Create new environment"
  ├─ Name: "Dev" / "Production"
  └─ Add variables:
     ├─ base_url = https://api.example.com
     ├─ api_key = abc123
     └─ timeout = 5000

Step 2: Use Variables in Request
  ├─ URL: /api/bmi/calculate
  ├─ Header: Authorization: Bearer 
  └─ Double curly braces for interpolation

Step 3: Select Environment
  └─ Top right dropdown → Select "Dev"

Step 4: Send
  └─ Variables will be replaced with actual values

6. Testing & Assertions

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
Adding Tests in Postman
═════════════════════════════════════════════════════════════

Step 1: Click "Tests" tab (next to Body)

Step 2: Write Test Code (JavaScript)
  └─ pm.test("Response status is 200", function () {
       pm.response.to.have.status(200);
     });
     
     pm.test("Response has BMI value", function () {
       var jsonData = pm.response.json();
       pm.expect(jsonData).to.have.property('bmi');
     });
     
     pm.test("BMI is positive", function () {
       var jsonData = pm.response.json();
       pm.expect(jsonData.bmi).to.be.above(0);
     });

Step 3: Send Request
  └─ Tests run automatically after response

Step 4: View Results
  ├─ Tests tab shows pass/fail
  └─ Console shows detailed output

Studi Kasus: Live Coding dengan Postman

Sekarang kita akan membuat API testing praktis menggunakan public API. Kami akan menggunakan JSONPlaceholder (fake REST API untuk testing).

Public API yang Digunakan

1
2
3
4
5
6
7
8
9
10
11
12
JSONPlaceholder: https://jsonplaceholder.typicode.com

Endpoints Tersedia:
  ✓ /posts        - Blog posts
  ✓ /comments     - Comments on posts
  ✓ /users        - User data
  ✓ /todos        - Todo items
  ✓ /albums       - Photo albums
  ✓ /photos       - Photos
  ✓ /comments     - Comments

No authentication needed untuk testing!

Studi Kasus 1: GET Request (Retrieve Data)

Request Details

1
2
3
4
Method:  GET
URL:     https://jsonplaceholder.typicode.com/posts/1
Headers: Accept: application/json
Purpose: Retrieve a specific blog post

Step-by-Step di Postman

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
STEP 1: Setup Request
─────────────────────
1. Open Postman
2. Click "+" untuk new request
3. Method: GET (dari dropdown)
4. URL: https://jsonplaceholder.typicode.com/posts/1

STEP 2: Add Headers
────────────────────
1. Click "Headers" tab
2. Add header:
   Key: Accept
   Value: application/json

STEP 3: Add Tests
─────────────────
1. Click "Tests" tab
2. Paste test code:

pm.test("Status code is 200", function () {
    pm.response.to.have.status(200);
});

pm.test("Response is JSON", function () {
    pm.response.to.be.json;
});

pm.test("Response has required fields", function () {
    var jsonData = pm.response.json();
    pm.expect(jsonData).to.have.property('id');
    pm.expect(jsonData).to.have.property('title');
    pm.expect(jsonData).to.have.property('body');
    pm.expect(jsonData).to.have.property('userId');
});

pm.test("Post ID is 1", function () {
    var jsonData = pm.response.json();
    pm.expect(jsonData.id).to.eql(1);
});

STEP 4: Send Request
────────────────────
1. Click "Send" button
2. Wait for response

Expected Response

1
2
3
4
5
6
{
  "userId": 1,
  "id": 1,
  "title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
  "body": "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut et ipsa possimus\nipsam odit\nsaepe nihil ipsa voluptatibus in\nsilentium autem doloribus maxime quam faucibus quis ipsa expedita\njn"
}

Response Analysis

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
Response Overview:
├─ Status: 200 OK ✓
├─ Response Time: ~150ms
├─ Response Size: ~284 bytes
├─ Content-Type: application/json
└─ Headers:
   ├─ Date: [timestamp]
   ├─ Server: cloudflare
   └─ X-Powered-By: Express

Response Body:
├─ userId: 1 (integer)
├─ id: 1 (integer)
├─ title: [string]
└─ body: [string with newlines]

Test Results:
✓ Status code is 200
✓ Response is JSON
✓ Response has required fields
✓ Post ID is 1

Studi Kasus 2: GET Request (List with Query Parameters)

Scenario

1
Retrieve posts by specific user with pagination

Request Details

1
2
3
Method:  GET
URL:     https://jsonplaceholder.typicode.com/posts?userId=1&_limit=5&_sort=id&_order=asc
Purpose: Get 5 posts from user 1, sorted by ID ascending

Step-by-Step di Postman

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
STEP 1: Build URL with Query Parameters
──────────────────────────────────────────
Option A: Direct in URL
  https://jsonplaceholder.typicode.com/posts?userId=1&_limit=5&_sort=id&_order=asc

Option B: Using Params Tab (Recommended)
  1. Click "Params" tab
  2. Add key-value pairs:
     ├─ userId = 1
     ├─ _limit = 5
     ├─ _sort = id
     └─ _order = asc
  3. Postman will auto-build URL

STEP 2: Add Tests
─────────────────
pm.test("Status code is 200", function () {
    pm.response.to.have.status(200);
});

pm.test("Response is array", function () {
    var jsonData = pm.response.json();
    pm.expect(jsonData).to.be.an('array');
});

pm.test("Response contains 5 items", function () {
    var jsonData = pm.response.json();
    pm.expect(jsonData).to.have.lengthOf(5);
});

pm.test("All posts belong to user 1", function () {
    var jsonData = pm.response.json();
    jsonData.forEach(function(post) {
        pm.expect(post.userId).to.eql(1);
    });
});

pm.test("Posts are sorted by ID ascending", function () {
    var jsonData = pm.response.json();
    for(let i = 1; i < jsonData.length; i++) {
        pm.expect(jsonData[i].id).to.be.greaterThan(jsonData[i-1].id);
    }
});

pm.test("Response time is less than 1 second", function () {
    pm.expect(pm.response.responseTime).to.be.below(1000);
});

STEP 3: Send
────────────
Click Send button

Expected Response

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
[
  {
    "userId": 1,
    "id": 1,
    "title": "sunt aut facere repellat...",
    "body": "quia et suscipit..."
  },
  {
    "userId": 1,
    "id": 2,
    "title": "qui est esse",
    "body": "est rerum tempore vitae..."
  },
  {
    "userId": 1,
    "id": 3,
    "title": "ea molestias quasi exercitationem...",
    "body": "et iusto sed quo iure..."
  },
  {
    "userId": 1,
    "id": 4,
    "title": "eum et est occaecati",
    "body": "ullam et saepe rebus..."
  },
  {
    "userId": 1,
    "id": 5,
    "title": "nesciunt quas odio",
    "body": "repudiandae veniam quaerat..."
  }
]

Studi Kasus 3: POST Request (Create Data)

Scenario

1
Create a new blog post in the system

Request Details

1
2
3
4
5
6
7
8
9
Method:  POST
URL:     https://jsonplaceholder.typicode.com/posts
Headers: Content-Type: application/json
Body:    {
           "title": "My API Test Post",
           "body": "This is a test post created via API",
           "userId": 1
         }
Purpose: Create a new blog post

Step-by-Step di Postman

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
STEP 1: Setup Request
──────────────────────
1. Method: POST
2. URL: https://jsonplaceholder.typicode.com/posts

STEP 2: Add Headers
───────────────────
1. Click "Headers" tab
2. Add:
   Key: Content-Type
   Value: application/json

STEP 3: Add Request Body
────────────────────────
1. Click "Body" tab
2. Select "raw" option
3. Select "JSON" from dropdown
4. Enter body:

{
  "title": "My API Test Post",
  "body": "This is a test post created via API. Testing POST request in Postman.",
  "userId": 1
}

STEP 4: Add Pre-request Script
──────────────────────────────
1. Click "Pre-request Script" tab
2. Add script to set timestamp:

var timestamp = new Date().toISOString();
pm.environment.set("request_timestamp", timestamp);
console.log("Request sent at: " + timestamp);

STEP 5: Add Tests
─────────────────
pm.test("Status code is 201 Created", function () {
    pm.response.to.have.status(201);
});

pm.test("Response is JSON", function () {
    pm.response.to.be.json;
});

pm.test("Response has ID", function () {
    var jsonData = pm.response.json();
    pm.expect(jsonData).to.have.property('id');
    pm.expect(jsonData.id).to.be.a('number');
});

pm.test("Response contains all input fields", function () {
    var jsonData = pm.response.json();
    pm.expect(jsonData.title).to.eql("My API Test Post");
    pm.expect(jsonData.body).to.include("Testing POST request");
    pm.expect(jsonData.userId).to.eql(1);
});

pm.test("Response contains expected fields", function () {
    var jsonData = pm.response.json();
    pm.expect(jsonData).to.have.property('id');
    pm.expect(jsonData).to.have.property('title');
    pm.expect(jsonData).to.have.property('body');
    pm.expect(jsonData).to.have.property('userId');
});

// Store ID in environment for later use
pm.environment.set("created_post_id", jsonData.id);
pm.test("ID stored in environment", function () {
    pm.expect(pm.environment.get("created_post_id")).to.exist;
});

STEP 6: Send
────────────
Click Send button

Expected Response

1
2
3
4
5
6
{
  "title": "My API Test Post",
  "body": "This is a test post created via API. Testing POST request in Postman.",
  "userId": 1,
  "id": 101
}

Response Analysis

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
Status: 201 Created ✓
  └─ Indicates successful resource creation

Response Body:
  ├─ id: 101 (newly generated)
  ├─ title: "My API Test Post" ✓
  ├─ body: "This is a test..." ✓
  └─ userId: 1 ✓

Test Results:
  ✓ Status code is 201 Created
  ✓ Response is JSON
  ✓ Response has ID
  ✓ Response contains all input fields
  ✓ Response contains expected fields
  ✓ ID stored in environment

Studi Kasus 4: Using Environments for Different Endpoints

Create Environment

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
STEP 1: Create Environment
──────────────────────────
1. Top right → "No Environment" dropdown
2. Click → "Create new environment"
3. Name: "JSONPlaceholder"
4. Add Variables:
   ├─ base_url: https://jsonplaceholder.typicode.com
   ├─ endpoint: /posts
   ├─ post_id: 1
   ├─ user_id: 1
   └─ limit: 5

5. Save environment

STEP 2: Update Request to Use Variables
───────────────────────────────────────
1. URL: /
2. Params:
   ├─ userId = 
   ├─ _limit = 
   └─ _sort = id

3. Select Environment: JSONPlaceholder
4. Send

STEP 3: Change Endpoint by Updating Variables
──────────────────────────────────────────────
To test different endpoints:
1. Click Environment eye icon
2. Edit variables:
   ├─ endpoint: /comments → Test comments endpoint
   ├─ endpoint: /users → Test users endpoint
   └─ endpoint: /todos → Test todos endpoint
3. Same request URL works for all!

Studi Kasus 5: Testing Error Scenarios

Test Invalid Request

1
2
3
4
5
6
7
8
Request Details:
─────────────────
Method:  GET
URL:     https://jsonplaceholder.typicode.com/posts/99999

Purpose: Test behavior for non-existent resource

Expected: 404 Not Found

Test Code

1
2
3
4
5
6
7
8
9
10
11
12
pm.test("Status code is 404 for non-existent resource", function () {
    pm.response.to.have.status(404);
});

pm.test("Response body is empty object", function () {
    var jsonData = pm.response.json();
    pm.expect(Object.keys(jsonData).length).to.equal(0);
});

pm.test("Response time is minimal", function () {
    pm.expect(pm.response.responseTime).to.be.below(500);
});

Studi Kasus 6: Creating a Collection

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
COLLECTIONS - Organize related requests
═════════════════════════════════════════════════════════════

STEP 1: Create Collection
───────────────────────────
1. Left sidebar → Collections
2. Click "+" (New Collection)
3. Name: "JSONPlaceholder Tests"
4. Description: "Test collection for JSONPlaceholder API"
5. Save

STEP 2: Add Requests to Collection
───────────────────────────────────
1. Create GET request
2. Click Save
3. Select collection: JSONPlaceholder Tests
4. Name: "Get Single Post"
5. Save

Repeat for:
  - Get All Posts
  - Create Post
  - Update Post (PUT)
  - Delete Post
  - Get User Posts
  - Get Comments

STEP 3: Create Folders
──────────────────────
1. Right-click on collection
2. Add Folder: "Posts"
3. Add Folder: "Comments"
4. Add Folder: "Users"

STEP 4: Organize Requests
──────────────────────────
1. Drag requests into folders
2. Posts:
   ├─ Get All Posts
   ├─ Get Single Post
   ├─ Create Post
   └─ Delete Post

3. Comments:
   ├─ Get Comments
   └─ Create Comment

4. Users:
   ├─ Get All Users
   ├─ Get Single User
   └─ Get User Posts

STEP 5: Run Collection
──────────────────────
1. Click collection menu (...)
2. Select "Run collection"
3. Environment: JSONPlaceholder
4. Execution details will show

Best Practices

API Testing Best Practices

1. Organize Tests in Collections

1
2
3
4
5
6
7
8
9
10
✅ DO: Logical organization
  └─ Collections by feature/module
     ├─ Authentication
     ├─ Users
     ├─ Posts
     ├─ Comments
     └─ Admin

❌ DON'T: Random unorganized requests
  └─ No structure, hard to find

2. Use Environments for Configuration

1
2
3
4
5
6
7
8
9
✅ DO: Use variables & environments
  ├─ Development environment
  ├─ Staging environment
  ├─ Production environment
  └─ Same tests run against all

❌ DON'T: Hardcode URLs & credentials
  └─ Cannot easily switch environments
  └─ Security risk

3. Test Both Happy & Sad Paths

1
2
3
4
5
6
7
8
✅ DO: Comprehensive test coverage
  ├─ Happy path (success scenarios)
  ├─ Error path (validation errors)
  ├─ Edge cases (boundary values)
  └─ Security scenarios

❌ DON'T: Only test success scenarios
  └─ Miss error handling issues

4. Write Descriptive Test Names

1
2
3
4
5
6
7
✅ DO: Clear test names
  └─ test_status_code_is_200_for_valid_post
  └─ test_error_for_missing_required_field

❌ DON'T: Vague names
  └─ test_post
  └─ test_api

5. Use Assertions Effectively

1
2
3
4
5
6
7
✅ DO: Multiple specific assertions
  └─ pm.expect(status).to.eql(200)
  └─ pm.expect(response).to.have.property('id')
  └─ pm.expect(response.bmi).to.be.above(0)

❌ DON'T: Just check status code
  └─ pm.response.to.have.status(200)  // Only this

6. Document API Behavior

1
2
3
4
5
6
7
✅ DO: Document in Postman
  └─ Request descriptions
  └─ Response examples
  └─ Error scenarios
  └─ Rate limits

Result: Self-documenting API tests

7. Automate Testing Pipeline

1
2
3
4
5
6
7
8
9
✅ DO: Integrate with CI/CD
  └─ Run tests automatically
  └─ On every commit
  └─ Using Newman CLI
  └─ Generate reports

❌ DON'T: Manual testing only
  └─ Time-consuming
  └─ Error-prone

8. Test Performance

1
2
3
4
5
6
7
8
✅ DO: Include performance checks
  └─ Response time < 500ms
  └─ Response size < 1MB
  └─ JSON parsing works
  └─ No memory leaks

❌ DON'T: Ignore performance
  └─ Slow APIs frustrate users

Kesimpulan

Key Takeaways

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
✅ API TESTING BENEFITS:
   ✓ Early detection of issues
   ✓ Core functionality verification
   ✓ Security verification
   ✓ Performance measurement
   ✓ Regression prevention
   ✓ Living documentation
   ✓ Cost effective

✅ POSTMAN ADVANTAGES:
   ✓ User-friendly interface
   ✓ No coding required for basic tests
   ✓ Collections for organization
   ✓ Environments for flexibility
   ✓ Built-in assertions
   ✓ CI/CD integration (Newman)
   ✓ Large community & resources

✅ CORE CONCEPTS:
   ✓ REST API principles
   ✓ HTTP methods (GET, POST, PUT, DELETE)
   ✓ Status codes (2xx, 4xx, 5xx)
   ✓ Request/Response structure
   ✓ Headers, body, parameters
   ✓ Authentication & authorization

✅ BEST PRACTICES:
   ✓ Organize in collections
   ✓ Use environments
   ✓ Test happy & sad paths
   ✓ Write descriptive names
   ✓ Use effective assertions
   ✓ Document behavior
   ✓ Automate & integrate
   ✓ Test performance

Next Steps

  1. Download Postman: https://www.postman.com/downloads/
  2. Create Free Account: Sign up for free tier
  3. Try Public APIs: JSONPlaceholder, OpenWeatherMap, etc.
  4. Build Collections: Organize your tests
  5. Learn Scripting: JavaScript for advanced tests
  6. Automate: Integrate with CI/CD (Newman)
  7. Explore Advanced: Mock servers, monitoring, etc.

Resources


Happy API Testing! 🚀

This post is licensed under CC BY 4.0 by the author.