An open API service indexing awesome lists of open source software.

https://github.com/weaponsforge/ph-regions

A RESTful API that serves hierarchical (regions, provinces municipalities) location test data of the Philippines
https://github.com/weaponsforge/ph-regions

api-documentation mongodb mongoose openapi3 rest-api tools

Last synced: 3 months ago
JSON representation

A RESTful API that serves hierarchical (regions, provinces municipalities) location test data of the Philippines

Awesome Lists containing this project

README

          

## ph-regions

A RESTful API that serves **hierarchical location data** of the Philippines β€” including regions, provinces, municipalities, and a **randomly generated number of barangays** per municipality.

> [!IMPORTANT]
> This API is intended **for testing and simulating RESTful API requests** from client applications.

> **Note:** The location data may be outdated and does **not** reflect the most current official records.

[![DeepWiki](https://img.shields.io/badge/DeepWiki-weaponsforge%2Fph--regions-blue.svg?logo=data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACwAAAAyCAYAAAAnWDnqAAAAAXNSR0IArs4c6QAAA05JREFUaEPtmUtyEzEQhtWTQyQLHNak2AB7ZnyXZMEjXMGeK/AIi+QuHrMnbChYY7MIh8g01fJoopFb0uhhEqqcbWTp06/uv1saEDv4O3n3dV60RfP947Mm9/SQc0ICFQgzfc4CYZoTPAswgSJCCUJUnAAoRHOAUOcATwbmVLWdGoH//PB8mnKqScAhsD0kYP3j/Yt5LPQe2KvcXmGvRHcDnpxfL2zOYJ1mFwrryWTz0advv1Ut4CJgf5uhDuDj5eUcAUoahrdY/56ebRWeraTjMt/00Sh3UDtjgHtQNHwcRGOC98BJEAEymycmYcWwOprTgcB6VZ5JK5TAJ+fXGLBm3FDAmn6oPPjR4rKCAoJCal2eAiQp2x0vxTPB3ALO2CRkwmDy5WohzBDwSEFKRwPbknEggCPB/imwrycgxX2NzoMCHhPkDwqYMr9tRcP5qNrMZHkVnOjRMWwLCcr8ohBVb1OMjxLwGCvjTikrsBOiA6fNyCrm8V1rP93iVPpwaE+gO0SsWmPiXB+jikdf6SizrT5qKasx5j8ABbHpFTx+vFXp9EnYQmLx02h1QTTrl6eDqxLnGjporxl3NL3agEvXdT0WmEost648sQOYAeJS9Q7bfUVoMGnjo4AZdUMQku50McDcMWcBPvr0SzbTAFDfvJqwLzgxwATnCgnp4wDl6Aa+Ax283gghmj+vj7feE2KBBRMW3FzOpLOADl0Isb5587h/U4gGvkt5v60Z1VLG8BhYjbzRwyQZemwAd6cCR5/XFWLYZRIMpX39AR0tjaGGiGzLVyhse5C9RKC6ai42ppWPKiBagOvaYk8lO7DajerabOZP46Lby5wKjw1HCRx7p9sVMOWGzb/vA1hwiWc6jm3MvQDTogQkiqIhJV0nBQBTU+3okKCFDy9WwferkHjtxib7t3xIUQtHxnIwtx4mpg26/HfwVNVDb4oI9RHmx5WGelRVlrtiw43zboCLaxv46AZeB3IlTkwouebTr1y2NjSpHz68WNFjHvupy3q8TFn3Hos2IAk4Ju5dCo8B3wP7VPr/FGaKiG+T+v+TQqIrOqMTL1VdWV1DdmcbO8KXBz6esmYWYKPwDL5b5FA1a0hwapHiom0r/cKaoqr+27/XcrS5UwSMbQAAAABJRU5ErkJggg==)](https://deepwiki.com/weaponsforge/ph-regions)

### Online Demo

- REST API:
- API documentation
- Static:
- Interactive:


![architecture](assets/architecture.png)



### Local Development Screenshots


Static API docs screenshot
Interactive API docs screenshot

### Table of Contents

- [Requirements](#-requirements)
- [Core Libraries/Frameworks](#-core-librariesframeworks)
- [Project Folder Structure](#-project-folder-structure)
- [Quickstart](#-quickstart)
- [Installation](#️-installation)
- [Usage](#-usage)
- [Using Docker](#-using-docker)
- [Alternate Usage Using Node](#-alternate-usage-using-node)
- [Available Scripts](#-available-scripts)
- [Docker Scripts](#-docker-scripts)
- [Adding New Endpoints](#️-adding-new-endpoints)
- [Usage with GitHub Actions](#usage-with-github-actions)
- [References](#references)

## Contributing

We welcome contributions! Please see [CONTRIBUTING.md](./CONTRIBUTING.md) for guidelines.

## πŸ“‹ Requirements

1. NodeJS LTS >= v22
2. Docker

### πŸ“¦ Core Libraries/Frameworks

πŸ‘‰ The server app uses the following core libraries and frameworks.

| Library | Version | Description |
| --- | --- | --- |
| Express | `5.1.0` | Node.js web framework for building APIs and web servers. |
| Mongoose | `8.16.5` | ODM for MongoDB that provides schema-based modeling and data interaction. |
| Zod | `4.0.10` | TypeScript-first schema validation for request payloads and query parameters. |
| Nodemon | `3.1.10` | Development tool that automatically restarts the server on file changes. |
| tsx | `4.20.3` | Executes TypeScript and TSX files directly, ideal for dev and script running. |
| tsc-alias | `1.8.16` | Rewrites path aliases in compiled TypeScript output (`tsconfig` paths). |
| ESlint | `9.32.0` | Linting tool that enforces code style, quality, and formatting rules. |
| @asteasolutions/zod-to-openapi | `8.1.0` | Generates OpenAPI YAML and JSON files from Zod schemas. |
| @redocly/cli | `2.1.0` | Generates an API documentation using an OpenAPI YAML input. |
| swagger-ui-express | `4.1.8` | Generates a Swagger UI API documentation using an OpenAPI JSON input. |


## πŸ“š Project Folder Structure

The main app is inside the `πŸ“‚ server/src` folder.

- πŸ“‚ **dist** - Contains the compiled JavaScript output from TypeScript.
- 🧩 **classes** - Contains reusable class-based logic and services.
- βš™οΈ **controllers** - Contains scripts for handling incoming HTTP requests and responses.
- πŸ”— **middleware** - Contains functions that process HTTP requests before controllers.
- 🧊 **models** - Contains MongoDB database models and schema definitions using Mongoose.
- πŸͺ§ **routes** - Contains API endpoint definitions and route bindings.
- πŸ“ **schemas** - Contains Zod validation schemas.
- πŸ“œ **scripts** - Contains utility scripts for setup and maintenance tasks.
- 🌐 **openapi** - Contains OpenAPI definitions using Zod schemas (folder: `/scripts/openapi/docs`)
- 🧾 **types** - Contains shared TypeScript types and interfaces
- πŸ› οΈ **utils** - Contains general-purpose helper functions.
- πŸ“± `app.ts` - Sets up the Express app and middleware.
- πŸ–₯️ `server.ts` - Starts the server and listens for requests


## πŸ†• Quickstart

Follow these steps to set up and use the code repository easily. Read the [Installation](#️-installation) section for detailed setup and usage instructions.

1. Create a `.env` file in the `/server` directory, copying the contents of the `.env.example` file.

2. Build the development images.

`docker compose build`

3. Run the development containers.

`docker compose up`

4. Create initial data.

`docker exec -it weaponsforge-ph-regions npm run seed`

5. Access the available resources:
- REST API documentation: http://localhost:3001
- REST API endpoints: http://localhost:3001/api

## πŸ› οΈ Installation

1. Clone the repository.

`git clone https://github.com/weaponsforge/ph-regions.git`

2. This repository promotes the use of Docker (See [Using Docker](#-using-docker)) to run the local app. Install dependencies only when proceeding to use the [**"Alternate Usage Using Node"**](#-alternate-usage-using-node) option.

```sh
cd server
npm install
```

3. Create a `.env` file from the `.env.example` file using its default values in the `/server` directory. Edit the variables and values as needed.


πŸ‘‰ List of Environment Variables

| Variable Name | Description |
| --- | --- |
| ALLOW_ALL_ORIGINS | Flag to allow HTTP requests from all origins (domains). When set to `1` (default), enables CORS for all domains. When set to `0`, restricts access to domains specified in `ALLOWED_ORIGINS`. |
| ALLOW_CORS | Enable Cross-Origin Resource Sharing (CORS) on the API endpoints from whitelisted domains, if `ALLOW_ALL_ORIGINS=0`.

`ALLOW_CORS=1` enables CORS for specified `ALLOWED_ORIGINS` and restricts access to those domains.
`ALLOW_CORS=0` disables CORS restrictions, allowing all domains including Postman. |
| ALLOWED_ORIGINS | IP/domain origins in comma-separated values that are allowed to access the API if `ALLOW_CORS=1` and `ALLOW_ALL_ORIGINS=0`.
Include `http://localhost:3000` by default to allow CORS access to the **/client** app. |
| DEPLOYMENT_PLATFORM | This variable refers to the backend `server`'s hosting platform, defaulting to `DEPLOYMENT_PLATFORM=regular`
for full-server NodeJS express apps.

Valid values are:
`regular` - for traditional full-server NodeJS express apps
`vercel` - for Vercel (serverless) |
| MONGO_URI | MongoDB connection string.
Default value uses the Docker MongoDB connection string (defined in the docker compose file). |
| BASE_API_URL | Server base API url minus the forward slash |
| CHOKIDAR_USEPOLLING | Enables hot reload on `nodemon` running inside Docker containers on a Windows host. Set it toΒ `true`Β if running Docker Desktop with WSL2 on a Windows OS. |
| CHOKIDAR_INTERVAL | Chokidar polling interval. Set it along with `CHOKIDAR_USEPOLLING=true` if running Docker Desktop with WSL2 on a Windows OS. The default value is `1000`. |

4. Seed (create) the initial data set.

- This step requires running the `"npm run seed"` script.
- Proceed to the [**"Using Docker"**](#-using-docker) section for more information on running the app first using Docker.
- Run the command after successfully running the server app using Docker from [A. Use Pre-Built Development Docker Image](#a-use-pre-built-development-docker-image) or [B. Build the Development Docker Image](#b-build-the-development-docker-image).
```sh
docker exec -it weaponsforge-ph-regions npm run seed
```

## ⚑ Usage

### 🐳 Using Docker

### A. Use Pre-Built Development Docker Image

See [Docker Hub: weaponsforge/ph-regions](https://hub.docker.com/r/weaponsforge/ph-regions)

1. Pull the development Docker image from Docker Hub using one of the options.

- `docker pull weaponsforge/ph-regions:latest`
- `docker compose pull` (using Docker compose from the root project directory)

2. Navigate to the project directory. Create a `.env` file at **server/.env** using **server/.env.example** as reference.
- See [Installation](#️-installation) - **step # 3** for more information.

3. Run the development Docker image.

- ```sh
docker compose up
```

- Proceed to **Build the Development Docker Image - step # 2** for more information.

### B. Build the Development Docker Image

1. Build the image.

```sh
docker compose build --no-cache
```

2. Run the container.

```sh
docker compose up
```
- > πŸ’‘ **INFO:** Windows OS users may need to uncomment the `CHOKIDAR_USEPOLLING` and `CHOKIDAR_INTERVAL` environment variables to enable hot reload.
- > πŸ”„ **Alternate Run Command**

> Run this command instead of the first one to enable debugging with breakpoints in VS Code.

```sh
docker compose -f docker-compose.debug.yml up
```

3. Confirm the running containers.
```sh
docker ps

// -- weaponsforge-ph-regions (this app)
// -- mongodb-ph-regions (Mongo DB service)
```

4. πŸ’‘ Launch the API documentation to view available endpoints.

```text
# Main API docs
http://localhost:3001

# Alternate API docs (interactive)
http://localhost:3001/docs
```

5. View the [Available Scripts](#-available-scripts) to run.

6. Stop the containers to exit.

```sh
docker compose down
```

### 🟩 Alternate Usage Using Node

> [!NOTE]
> Running the server directly with Node.js requires a locally installed and accessible MongoDB instance, which may need to be set up manually.

>
> When using a different MongoDB service or installation (other than the one provided in the Docker Compose setup), ensure the `MONGO_URI` variable in the `.env` file is properly configured.

πŸ‘‰ View usage instructions

1. Build the API documentation.

```sh
# Builds the Redocly API documentation
npm run docs:build
```

```sh
# Builds the Swagger UI API documentation
npm run docs:swagger
```

2. Run the seeder script only once.

```sh
npm run seed
```

3. Run the API for local development.

```sh
npm run dev
```

4. πŸ’‘ Launch the API documentation to view available endpoints.

```text
# Main API docs
http://localhost:3001

# Alternate API docs (interactive)
http://localhost:3001/docs
```

5. View the [Available Scripts](#-available-scripts) to run.


## πŸ“œ Available Scripts

These scripts, defined in the `"/server/package.json"` file, are compatible with running in Node and Docker. They run various TypeScript scripts, tests, and processes for code base management.

πŸ‘‰ Click to expand the list of available scripts

### `npm start`

Runs the compiled (JavaScript) server app for production mode.

### `npm run dev`

Runs the app for local development (when using Node).

### `npm run transpile`

Builds JavaScript, `.d.ts` declaration files, and map files from the TypeScript source files.

### `npm run transpile:noemit`

Runs type-checking without generating the JavaScript or declaration files from the TypeScript files.

### `npm run watch`

Watches file changes in `.ts` files using the `tsc --watch` option.

### `npm run lint`

Lints TypeScript source codes.

### `npm run lint:fix`

Fixes lint errors in TypeScript files.

### `npm run seed`

Runs the database seeder script, inserting initial data contents to the database.

### `npm run docs:gen`

Generates the OpenAPI `openapi.yaml` (YAML) and `openapi.json` (JSON) files into the `/server/public` directory.

> πŸ’‘ **NOTE:** Comment out **Line #21, under [public folder volume]** in the `docker-compose.yml` file to update the `"/server/public/openapi.yaml"` and `"/server/public/openapi.json"` files in the host volume.

### `npm run docs:build`

Builds the API documentation using the [Redocly CLI](https://www.npmjs.com/package/@redocly/cli) into the `/server/public/index.html` file.

### `npm run build`

Standard NPM build script that runs transpile, builds OpenAPI docs, and copies Swagger UI assets (`transpile` + `docs:build` + `docs:swagger`).

> πŸ’‘ **NOTE:** Comment out **Line #21 under [public folder volume]** in the `docker-compose.yml` file when running this script via Docker to resolve `EACCES: permission denied` errors.

### `npm run docs:swagger`

Copies the minimal Swagger UI assets (CSS/JS) from `node_modules` into `/public/docs`. The page `public/docs/index.html` references these assets and the generated OpenAPI spec in `/public/openapi.json`

> πŸ’‘ **NOTE:** Comment out **Line #21, under [public folder volume]** in the `docker-compose.yml` file when running this script via Docker to resolve `EACCES: permission denied` errors.


## πŸ“¦ Docker Scripts

These scripts allow optional Docker-related processes, such as enabling file watching in Docker containers running in Windows WSL2 and others.

πŸ‘‰ Click to expand the list of available scripts

### Docker run command

```sh
docker exec -it weaponsforge-ph-regions
```

### `npm run docker:dev`

Runs the app for local development with the `--inspect` flag, enabling it for debugging with breakpoints in VS Code when running inside containers.

### `npm run docker:seed:debug`

Runs the database seeder script, inserting initial data contents to the database.

```sh
docker exec -it weaponsforge-ph-regions npm run docker:seed:debug
```

> πŸ”” **IMPORTANT**

> This script requires having run only the `docker compose up` command. This ensures port `9229` is free for watching the script since it does not run the nodemon + server app with `tsx` and `--inspect=0.0.0.0:9229`.

### `npm run docker:watch:win`

Watches file changes in `.ts` files using the `tsc --watch` option with `dynamicPriorityPolling` in Docker containers running in Windows WSL2.


## πŸ—‚οΈ Adding New Endpoints

Follow the steps for adding (or editing) new endpoints to the API.

πŸ‘‰ Click to view the guidelines

1. **Create a Zod schema**
- Follow the patterns in the `πŸ“ schemas` directory (e.g., `province.schema.ts`).
- Ensure each schema field has a Zod `.meta()` attached, with a `description` key containing a short description of the field, and an `example`.
2. **Create a Mongoose model**
- Follow the patterns in the `🧊 models` directory (e.g., `province.model.ts`).
- The Zod-inferred type (`z.infer()`) of the **Zod Schema** created in **step # 1** should be used to type-cast this model's **Mongoose Schema**.

3. **Set up routes (API endpoints)**

Add new routes for the model in the `πŸͺ§ routes` directory (e.g., `/routes/province.ts`) **without input validation** for now.

4. **Define query, response, and request schemas**

Create Zod schemas for HTTP query, response, params, and body in:

`server/src/scripts/openapi/docs/api.schema.ts`

> πŸ’‘ **INFO**

Follow the existing schema patterns in this file.

5. **Add validation middleware**

- Implement `πŸ”— validation` middleware for the routes (from **step 3**) using the Zod schemas from **step 4**.
- Attach this middleware to the routes.

6. **Document with OpenAPI**

Create OpenAPI documentation for the model in the `🌐 openapi` directory (e.g., `/scripts/openapi/docs/province.doc.ts`) and **register it** in `main.ts`.

7. **Create a controller**

Add model-specific business logic in the `βš™οΈ controllers` directory (e.g., `/controllers/province.ts`) and connect it to the routes.

8. **Test the endpoints**

Perform manual tests to ensure everything works correctly.


## Usage with GitHub Actions

#### GitHub Secrets

| GitHub Secrets | Description |
| --- | --- |
| BASE_API_URL | The Vercel server base URL of the production ph-regions API minus the forward slash. |
| DOCKERHUB_USERNAME | Docker Hub username |
| DOCKERHUB_TOKEN | Deploy token for the Docker Hub account |
| VERCEL_ORG_ID | Vercel app's organization ID |
| VERCEL_PROJECT_ID | Vercel app's project ID |
| VERCEL_TOKEN | Vercel personal/token used by the CLI for auth in CI |
| DEPLOYMENT_PLATFORM | Target deployment platform of the backend server. Value is `vercel` |

#### GitHub Variables

| GitHub Variable | Description |
| --- | --- |
| DOCKERHUB_USERNAME | Docker Hub username |

### Deployment to Docker Hub

This repository deploys the latest development Docker imageΒ `weaponsforge/ph-regions:latest` to Docker Hub after creating new Tags/Releases with GitHub Actions. Supply the above-mentioned GitHub Secrets and Variables to enable deployment to Docker Hub. It requires a **Docker Hub account**.

The Docker Hub image is available at:

https://hub.docker.com/r/weaponsforge/ph-regions

### Deployment to Vercel

This repository deploys the latest production API and documentation to Vercel after creating new Tags/Releases with GitHub Actions. Supply the above-mentioned GitHub Secrets and Variables to enable deployment to Vercel. It also requires the following:

- An Express app initialized in a **Vercel project**
- **MongoDB Atlas** database (for the `MONGO_URI` environment variable in the Vercel project)

## References

- [OpenAPI Specification](https://swagger.io/specification/)
- [Redocly - Introduction to OpenAPI](https://redocly.com/learn/openapi/learning-openapi)
- [Redocly - API Governance](https://redocly.com/api-governance)
- [Redocly Configuration](https://redocly.com/docs/redoc/config)
- [Redocly CLI](https://www.npmjs.com/package/@redocly/cli)
- [Redocly CLI Cookbook](https://github.com/Redocly/redocly-cli-cookbook)
- [Redoc Demo](https://redocly.github.io/redoc/)
- [Swagger Editor (Online)](https://swagger.io/tools/swagger-editor/)

@weaponsforge

20250711

20250911