🚀 Big News:Socket Has Acquired Secure Annex.Learn More →
Socket
Book a DemoSign in
Socket

api-response-handler

Package Overview
Dependencies
Maintainers
1
Versions
8
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

api-response-handler

A universal API error handler for Node.js applications with standardized responses and error management.

latest
Source
npmnpm
Version
2.0.0
Version published
Maintainers
1
Created
Source

🚀 Api Response Handler

Api Response Handler is a utility library designed for consistent, standardized, and user-friendly API responses in Express.js applications. It simplifies success, error, validation, and pagination responses while reducing repetitive boilerplate code.

📦 Installation

Install the package via npm:

npm install api-response-handler

📚 Usage

âś… Import the Module

import HandleResponse from 'api-response-handler';

⚡ API Response Methods

🔹 1. Success Response

Send a generic success response.

app.get('/success', (req, res) => {
  HandleResponse.success(res, 'Data fetched successfully', { id: 1, name: 'Example' });
});

Response:

{
  "success": true,
  "message": "Data fetched successfully",
  "data": {
    "id": 1,
    "name": "Example"
  },
  "status": 200
}

🔹 2. Created Response

Send a success response specifically for resource creation.

app.post('/create', (req, res) => {
  HandleResponse.created(res, 'User created successfully', { id: 1 });
});

Response:

{
  "success": true,
  "message": "User created successfully",
  "data": {
    "id": 1
  },
  "status": 201
}

🔹 3. Validation Error

Handle validation failures.

app.post('/validate', (req, res) => {
  const errors = { field: 'email', message: 'Invalid email format' };
  HandleResponse.validationError(res, 'Validation failed', errors);
});

Response:

{
  "success": false,
  "message": "Validation failed",
  "details": {
    "field": "email",
    "message": "Invalid email format"
  },
  "status": 422
}

🔹 4. Unauthorized Access

Handle unauthorized access attempts.

app.get('/unauthorized', (req, res) => {
  HandleResponse.unauthorized(res);
});

Response:

{
  "success": false,
  "message": "Unauthorized Access",
  "status": 401
}

🔹 5. Forbidden Access

Handle forbidden requests.

app.get('/forbidden', (req, res) => {
  HandleResponse.forbidden(res);
});

Response:

{
  "success": false,
  "message": "Forbidden Access",
  "status": 403
}

🔹 6. Not Found

Handle requests to non-existent resources.

app.get('/not-found', (req, res) => {
  HandleResponse.notFound(res);
});

Response:

{
  "success": false,
  "message": "Resource Not Found",
  "status": 404
}

🔹 7. Server Error (Try-Catch Handling)

Handle unexpected server errors gracefully.

app.get('/server-error', (req, res) => {
  try {
    throw new Error('Unexpected error');
  } catch (error) {
    HandleResponse.serverError(res, error);
  }
});

Response:

{
  "success": false,
  "message": "Internal Server Error",
  "error": "Unexpected error",
  "status": 500
}

🔹 8. Paginated Response

Send a structured paginated response.

app.get('/paginated', (req, res) => {
  const data = [{ id: 1 }, { id: 2 }];
  HandleResponse.paginated(res, data, 1, 10, 50);
});

Response:

{
  "success": true,
  "message": "Data Retrieved Successfully",
  "data": [
    { "id": 1 },
    { "id": 2 }
  ],
  "pagination": {
    "page": 1,
    "limit": 10,
    "total": 50,
    "totalPages": 5
  },
  "status": 200
}

🔹 9. Generic Error

Send a custom error response with details.

app.get('/custom-error', (req, res) => {
  HandleResponse.genericError(res, 'Something went wrong', 400, { info: 'Custom issue' });
});

Response:

{
  "success": false,
  "message": "Something went wrong",
  "details": {
    "info": "Custom issue"
  },
  "status": 400
}

🔹 10. No Content

Send a 204 No Content response.

app.delete('/delete', (req, res) => {
  HandleResponse.noContent(res);
});

Response: (No Body Returned, HTTP Status Code 204)

📊 API Methods Overview

MethodParametersDescription
successres, message, data, statusGeneric success response
createdres, message, dataResource creation response
validationErrorres, message, detailsValidation error response
unauthorizedres, messageUnauthorized access
forbiddenres, messageForbidden access
notFoundres, messageResource not found
serverErrorres, error, messageServer error response
paginatedres, data, page, limit, total, messagePaginated response
genericErrorres, message, status, detailsCustom error response
noContentres, messageNo content response (204)

🤝 Contributing

Contributions are always welcome!

  • Open issues or feature requests on the GitHub repository.
  • Submit pull requests with descriptive explanations.

đź“„ License

This project is licensed under the MIT License.

🧑‍💻 Author

Pratik Panchal

Keywords

api

FAQs

Package last updated on 11 Jan 2025

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts