API Penerimaan Documentation

Complete API documentation for managing revenue and income data

📌 Version: 1.0.1
🔒 Authentication: JWT Bearer
🌐 Base URL: http://localhost:2002
⚙️ Environment: development

Welcome to API Penerimaan

The API Penerimaan is a robust REST API designed to manage revenue and income data. It provides comprehensive endpoints for creating, reading, updating, and deleting penerimaan (revenue/income) records with built-in authentication, pagination, and advanced filtering capabilities.

Key Features

  • JWT Authentication: Secure API access with Bearer token authentication
  • RESTful Design: Standard HTTP methods for all operations
  • Pagination Support: Efficient data retrieval with customizable page sizes
  • Advanced Filtering: Search and filter by multiple criteria
  • Soft Deletes: Safe data deletion without permanent loss
  • Rate Limiting: Built-in rate limiting (100 requests per 15 minutes)
  • Error Handling: Comprehensive error responses with meaningful messages

API Response Format

All API responses follow a consistent JSON structure for easy integration.

Success Response Example
{
  "success": true,
  "message": "Operation successful",
  "data": {
    "id": 1,
    "trxCode": "SPP-001",
    "date": "2026-05-12",
    "description": "Pendapatan SPP",
    "amount": 5000000,
    "type": "100"
  },
  "pagination": {
    "page": 1,
    "limit": 10,
    "total": 100,
    "totalPages": 10,
    "hasNextPage": true,
    "hasPrevPage": false
  }
}

Supported Response Codes

  • 200 OK: Request succeeded
  • 201 Created: Resource successfully created
  • 400 Bad Request: Invalid request parameters or validation error
  • 401 Unauthorized: Missing or invalid authentication token
  • 403 Forbidden: Account inactive or insufficient permissions
  • 404 Not Found: Resource not found
  • 409 Conflict: Duplicate data or state conflict
  • 500 Internal Server Error: Server error

Quick Start

Get up and running with the API Penerimaan in just a few minutes.

1. Get Your API Token

First, authenticate with your credentials to get a JWT token:

Login Request
POST /auth/login
Content-Type: application/json

{
  "username": "your-username",
  "password": "your-password"
}
Response
{
  "success": true,
  "message": "Login berhasil",
  "data": {
    "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."
  }
}

2. Create Your First Penerimaan Record

Use the token from step 1 to create a new penerimaan record:

Create Request
POST /penerimaan
Authorization: Bearer {your-token}
Content-Type: application/json

{
  "trxCode": "SPP-001",
  "date": "2026-05-12",
  "description": "Pendapatan SPP Bulan Juni 2026",
  "amount": 5000000,
  "type": "100"
}

3. Retrieve Your Data

Fetch a list of penerimaan records with pagination:

List Request
GET /penerimaan?page=1&limit=10&search=SPP
Authorization: Bearer {your-token}

Authentication

The API Penerimaan uses JWT (JSON Web Tokens) for authentication. All endpoints (except login and auth check) require a valid JWT token in the Authorization header.

How to Authenticate

  1. Send your credentials to the login endpoint
  2. Receive a JWT token in the response
  3. Include the token in all subsequent requests using the Bearer scheme

Token Format

Include your token in the Authorization header of every request:

Authorization Header
Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...

Token Expiration

Tokens have a limited lifetime. If your token expires, you'll receive a 401 Unauthorized response. Simply login again to get a new token.

Security Best Practices

  • Never expose your API token in client-side code or version control
  • Always transmit tokens over HTTPS
  • Rotate your credentials periodically
  • Use environment variables to store sensitive information
  • Implement proper error handling for 401 responses

Authentication Endpoints

POST /auth/login

Authenticate user credentials and receive a JWT token for subsequent API requests.

Request Body
Parameter Type Required Description
username string Yes Username for authentication
password string Yes User password
cURL
curl -X POST ${BASE_URL}/auth/login \
  -H "Content-Type: application/json" \
  -d '{
    "username": "admin",
    "password": "admin123"
  }'
200 OK
{
  "success": true,
  "message": "Login berhasil",
  "data": {
    "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySWQiOjEsInVzZXJuYW1lIjoiYWRtaW4iLCJpYXQiOjE2MjMzODAwMDAwMDB9.signature"
  }
}
401 Unauthorized
{
  "success": false,
  "message": "Username atau password salah",
  "error": "INVALID_CREDENTIALS"
}

Create Penerimaan

POST /penerimaan

Create a new penerimaan (revenue/income) record. All fields are required.

Request Body
Parameter Type Required Description
trxCode string Yes Unique transaction code (must be unique)
date string (date) Yes Date in YYYY-MM-DD format
description string Yes Description of the revenue/income
amount number Yes Amount (must be positive number)
type string Yes Type code (100, 200, 300, 400, 500, 600)
cURL
curl -X POST ${BASE_URL}/penerimaan \
  -H "Authorization: Bearer YOUR_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "trxCode": "SPP-001",
    "date": "2026-05-12",
    "description": "Pendapatan SPP Bulan Juni 2026",
    "amount": 5000000,
    "type": "100"
  }'
201 Created
{
  "success": true,
  "data": {
    "id": 1,
    "trxCode": "SPP-001",
    "date": "2026-05-12",
    "description": "Pendapatan SPP Bulan Juni 2026",
    "amount": 5000000,
    "type": "100"
  }
}
409 Conflict
{
  "success": false,
  "message": "Kode transaksi sudah digunakan",
  "error": "DUPLICATE_TRX_CODE"
}

List Penerimaan

GET /penerimaan

Retrieve a paginated list of penerimaan records with optional search and filtering.

Query Parameters
Parameter Type Default Description
page integer 1 Page number for pagination
limit integer 10 Items per page
search string - Search in description or trx_code
sort_field string id Field to sort by (id, date, amount, created_at)
sort_order string DESC Sort order (ASC or DESC)
date_from string (date) - Filter from date (YYYY-MM-DD)
date_to string (date) - Filter to date (YYYY-MM-DD)
type string - Filter by type
cURL
curl -X GET "${BASE_URL}/penerimaan?page=1&limit=10&search=SPP" \
  -H "Authorization: Bearer YOUR_TOKEN"
200 OK
{
  "success": true,
  "data": [
    {
      "id": 1,
      "trxCode": "SPP-001",
      "date": "2026-05-12",
      "description": "Pendapatan SPP Bulan Juni 2026",
      "amount": 5000000,
      "type": "100",
      "created_at": "2026-05-12T10:30:00Z"
    }
  ],
  "pagination": {
    "page": 1,
    "limit": 10,
    "total": 50,
    "totalPages": 5,
    "hasNextPage": true,
    "hasPrevPage": false
  }
}

Get Penerimaan Detail

GET /penerimaan/:id

Retrieve a single penerimaan record by ID.

Path Parameters
Parameter Type Description
id integer Penerimaan ID
cURL
curl -X GET ${BASE_URL}/penerimaan/1 \
  -H "Authorization: Bearer YOUR_TOKEN"
200 OK
{
  "success": true,
  "data": {
    "id": 1,
    "trxCode": "SPP-001",
    "date": "2026-05-12",
    "description": "Pendapatan SPP Bulan Juni 2026",
    "amount": 5000000,
    "type": "100",
    "created_at": "2026-05-12T10:30:00Z",
    "updated_at": "2026-05-12T10:30:00Z"
  }
}

Update Penerimaan

PUT /penerimaan/:id

Update an existing penerimaan record. All fields are required.

Path Parameters
Parameter Type Description
id integer Penerimaan ID
Request Body
Parameter Type Required Description
trxCode string Yes Transaction code
date string (date) Yes Date in YYYY-MM-DD format
description string Yes Description
amount number Yes Amount (positive number)
type string Yes Type code
cURL
curl -X PUT ${BASE_URL}/penerimaan/1 \
  -H "Authorization: Bearer YOUR_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "trxCode": "SPP-001",
    "date": "2026-05-15",
    "description": "Pendapatan SPP Bulan Juni 2026 (Updated)",
    "amount": 6000000,
    "type": "100"
  }'
200 OK
{
  "success": true,
  "data": {
    "id": 1,
    "trxCode": "SPP-001",
    "date": "2026-05-15",
    "description": "Pendapatan SPP Bulan Juni 2026 (Updated)",
    "amount": 6000000,
    "type": "100",
    "message": "Data penerimaan berhasil diperbarui"
  }
}

Delete Penerimaan

DELETE /penerimaan/:id

Delete (soft delete) a penerimaan record. The record will be marked as deleted but not permanently removed.

Path Parameters
Parameter Type Description
id integer Penerimaan ID
cURL
curl -X DELETE ${BASE_URL}/penerimaan/1 \
  -H "Authorization: Bearer YOUR_TOKEN"
200 OK
{
  "success": true,
  "message": "Data penerimaan berhasil dihapus"
}

Error Handling

The API returns consistent error responses with meaningful messages and error codes.

Error Response Structure

Error Response Format
{
  "success": false,
  "message": "Human-readable error message",
  "error": "ERROR_CODE",
  "fields": ["field1", "field2"]
}

Common Error Codes

  • VALIDATION_ERROR: Invalid or missing required fields
  • INVALID_CREDENTIALS: Wrong username or password
  • ACCOUNT_INACTIVE: User account is not active
  • DUPLICATE_TRX_CODE: Transaction code already exists
  • NOT_FOUND: Resource not found
  • DATA_ALREADY_JOURNALIZED: Record is journalized and cannot be modified
  • BCRYPT_ERROR: Password verification system error

Example Error Responses

Validation Error (400)
{
  "success": false,
  "message": "Field wajib diisi",
  "error": "VALIDATION_ERROR",
  "fields": ["trxCode", "date", "amount"]
}
Unauthorized (401)
{
  "success": false,
  "message": "Token tidak valid atau sudah kadaluarsa",
  "error": "INVALID_TOKEN"
}

Pagination

List endpoints support pagination to efficiently handle large datasets.

Pagination Parameters

  • page: Page number (starts from 1)
  • limit: Items per page (default: 10)

Pagination Response

All paginated endpoints return pagination metadata:

Pagination Object
{
  "pagination": {
    "page": 1,
    "limit": 10,
    "total": 125,
    "totalPages": 13,
    "hasNextPage": true,
    "hasPrevPage": false
  }
}

Example: Paginating Through Results

JavaScript Example
async function fetchAllPages() {
  let page = 1;
  let allData = [];
  
  while (true) {
    const response = await fetch(
      ${BASE_URL}/penerimaan?page=&limit=50,
      {
        headers: {
          'Authorization': 'Bearer YOUR_TOKEN'
        }
      }
    );
    
    const result = await response.json();
    allData = allData.concat(result.data);
    
    if (!result.pagination.hasNextPage) break;
    page++;
  }
  
  return allData;
}

Filtering & Search

The list endpoint supports multiple filtering and search options.

Search

Use the search parameter to search across multiple fields:

Search Example
GET /penerimaan?search=SPP
Authorization: Bearer YOUR_TOKEN

Date Range Filtering

Filter records by date range using date_from and date_to:

Date Range Example
GET /penerimaan?date_from=2026-01-01&date_to=2026-12-31
Authorization: Bearer YOUR_TOKEN

Type Filtering

Filter by specific type:

Type Filter Example
GET /penerimaan?type=100
Authorization: Bearer YOUR_TOKEN

Sorting

Sort results by any field in ascending or descending order:

Sorting Example
GET /penerimaan?sort_field=date&sort_order=DESC
Authorization: Bearer YOUR_TOKEN

Combined Filters

Combine multiple filters for precise results:

Combined Example
GET /penerimaan?search=SPP&type=100&date_from=2026-01-01&sort_field=amount&sort_order=DESC&page=1&limit=20
Authorization: Bearer YOUR_TOKEN

Best Practices

1. Token Management

  • Store tokens securely (use environment variables or secure storage)
  • Never expose tokens in client-side code or logs
  • Implement automatic token refresh on 401 responses
  • Use HTTPS for all API requests

2. Error Handling

  • Always check the success field in responses
  • Implement retry logic for network failures
  • Handle rate limiting (429) with exponential backoff
  • Log errors with context for debugging

3. Performance Optimization

  • Use pagination to limit response size
  • Implement caching for frequently accessed data
  • Use specific filters to reduce result sets
  • Batch operations when possible

4. Data Validation

  • Validate data on the client before sending requests
  • Use proper date formats (YYYY-MM-DD)
  • Ensure amounts are positive numbers
  • Check for unique transaction codes before creation

5. Rate Limiting

  • Respect the 100 requests per 15 minutes limit
  • Implement request queuing for high-volume operations
  • Monitor rate limit headers in responses
  • Use webhooks or polling intervals appropriately

Example: Robust API Client

JavaScript API Client
class PenerimaanAPI {
  constructor(baseURL, token) {
    this.baseURL = baseURL;
    this.token = token;
  }

  async request(endpoint, options = {}) {
    try {
      const response = await fetch(${this.baseURL}, {
        ...options,
        headers: {
          'Authorization': Bearer ,
          'Content-Type': 'application/json',
          ...options.headers
        }
      });

      const data = await response.json();

      if (!data.success) {
        throw new Error(data.message || 'Request failed');
      }

      return data;
    } catch (error) {
      console.error('API Error:', error);
      throw error;
    }
  }

  async create(penerimaanData) {
    return this.request('/penerimaan', {
      method: 'POST',
      body: JSON.stringify(penerimaanData)
    });
  }

  async list(params = {}) {
    const query = new URLSearchParams(params).toString();
    return this.request(/penerimaan?);
  }

  async get(id) {
    return this.request(/penerimaan/);
  }

  async update(id, data) {
    return this.request(/penerimaan/, {
      method: 'PUT',
      body: JSON.stringify(data)
    });
  }

  async delete(id) {
    return this.request(/penerimaan/, {
      method: 'DELETE'
    });
  }
}

// Usage
const api = new PenerimaanAPI('${BASE_URL}', 'YOUR_TOKEN');
const result = await api.list({ page: 1, limit: 10 });