Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save Kartik7974/ef9870e232e1bc881bdcaf511fd7daf3 to your computer and use it in GitHub Desktop.
Save Kartik7974/ef9870e232e1bc881bdcaf511fd7daf3 to your computer and use it in GitHub Desktop.
# Prime Number API - Node.js (Express)
## Files:
### package.json
```json
{
"name": "prime-api",
"version": "1.0.0",
"description": "Simple API to check if a number is prime",
"main": "index.js",
"scripts": {
"start": "node index.js"
},
"dependencies": {
"express": "^4.18.2"
}
}
```
### index.js
```javascript
const express = require('express');
const app = express();
const port = 3000;
function isPrime(n) {
if (n <= 1) return false;
if (n <= 3) return true;
if (n % 2 === 0 || n % 3 === 0) return false;
for (let i = 5; i * i <= n; i += 6) {
if (n % i === 0 || n % (i + 2) === 0) return false;
}
return true;
}
app.get('/isprime', (req, res) => {
const numberParam = req.query.number;
if (!numberParam) {
return res.status(400).json({ status: 'error', message: "Missing 'number' query parameter" });
}
const number = parseInt(numberParam, 10);
if (isNaN(number)) {
return res.status(400).json({ status: 'error', message: "'number' must be an integer" });
}
const result = isPrime(number);
const message = result ? `${number} is a prime number` : `${number} is not a prime number`;
res.json({ status: 'success', message });
});
app.listen(port, () => {
console.log(`Prime API listening at http://localhost:${port}`);
});
```
### README.md
```markdown
# Prime Number API - Node.js (Express)
## Overview
This is a simple Node.js API built using the Express framework. It exposes one endpoint `/isprime` that takes a number as a query parameter and returns whether the number is prime or not.
## Prerequisites
- Node.js and npm installed
## Setup and Running
1. Install dependencies:
```bash
npm install
```
2. Run the API server:
```bash
npm start
```
The server will start on port 3000.
## Testing the API
You can test the API using curl or a browser.
Example using curl:
```bash
curl "http://localhost:3000/isprime?number=17"
```
Expected response:
```json
{
"status": "success",
"message": "17 is a prime number"
}
```
Example with invalid input:
```bash
curl "http://localhost:3000/isprime?number=abc"
```
Expected response:
```json
{
"status": "error",
"message": "'number' must be an integer"
}
```
## Notes
- The API expects the `number` query parameter to be an integer.
- Numbers less than 2 are considered not prime.
- Basic error handling is implemented for missing or invalid parameters.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment