Skip to content

High-performance phone number validation REST API built with Zig and Google's libphonenumber. Fast, safe, and production-ready alternative to commercial APIs like Twilio Lookup.

License

Notifications You must be signed in to change notification settings

copyleftdev/phonecheck

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

5 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

πŸ“ž PhoneCheck - Expert-Level Phone Validation REST API

CI License: MIT Zig libphonenumber Production Ready

A high-performance, production-ready REST API for phone number validation built with Zig and wrapping Google's libphonenumber C++ library.

πŸš€ Free alternative to Twilio Lookup - Validate 10M numbers/month for $40 instead of $50,000

⚑ 2,500+ req/s throughput - Battle-tested with simulated annealing load analysis

πŸ”’ Memory-safe - Zig's compile-time guarantees + arena allocators

Documentation

πŸš€ Features

  • Industry-Standard Validation: Powered by Google's libphonenumber (used by Google, Android, iOS)
  • Zero-Copy FFI: Direct C/C++ interop with no marshalling overhead
  • Ultra-Fast: Zig's performance + libphonenumber's battle-tested algorithms
  • Comprehensive Analysis:
    • βœ… Validity checking (correct for region)
    • βœ… Possibility checking (correct length/structure)
    • βœ… Phone type detection (mobile, fixed-line, toll-free, etc.)
    • βœ… Region/country code extraction
    • βœ… Multiple format outputs (E.164, international, national)
    • βœ… Number comparison and matching
  • 190+ Countries: Full international support
  • REST API: Simple HTTP JSON interface
  • Production-Ready: CORS support, error handling, health checks

πŸ“‹ Prerequisites

System Dependencies

You need to install Google's libphonenumber C++ library:

Ubuntu/Debian:

sudo apt-get update
sudo apt-get install -y \
    libphonenumber-dev \
    libprotobuf-dev \
    libicu-dev \
    cmake \
    build-essential

macOS (Homebrew):

brew install libphonenumber protobuf icu4c

Arch Linux:

sudo pacman -S libphonenumber protobuf icu

Build from source (if packages not available):

# Clone and build libphonenumber
git clone https://github.com/google/libphonenumber.git
cd libphonenumber/cpp
mkdir build && cd build
cmake ..
make -j$(nproc)
sudo make install
sudo ldconfig

Zig

Install Zig 0.15.2 or later:

# Download from https://ziglang.org/download/
# Or use your package manager

πŸ”§ Installation

  1. Clone the repository:
git clone <your-repo>
cd phonecheck
  1. Build the C++ wrapper:
./build_wrapper.sh
  1. Build the Zig application:
zig build
  1. Run the server:
zig build run

The API will start on http://0.0.0.0:8080

πŸ“š API Documentation

Health Check

Endpoint: GET /health

Response:

{
  "status": "healthy",
  "service": "phonecheck",
  "version": "1.0.0"
}

Validate Phone Number

Endpoint: POST /validate

Request Body:

{
  "phone_number": "+14155552671",
  "region": "US"  // Optional: ISO 3166-1 alpha-2 country code
}

Response:

{
  "valid": true,
  "possible": true,
  "type": "FIXED_LINE_OR_MOBILE",
  "country_code": 1,
  "national_number": 4155552671,
  "region": "US",
  "e164_format": "+14155552671",
  "international_format": "+1 415-555-2671",
  "national_format": "(415) 555-2671",
  "possibility_reason": "IS_POSSIBLE"
}

Phone Types:

  • FIXED_LINE - Traditional landline
  • MOBILE - Mobile phone
  • FIXED_LINE_OR_MOBILE - Could be either
  • TOLL_FREE - Toll-free number
  • PREMIUM_RATE - Premium rate number
  • SHARED_COST - Shared cost service
  • VOIP - VoIP number
  • PERSONAL_NUMBER - Personal number
  • PAGER - Pager
  • UAN - Universal Access Number
  • VOICEMAIL - Voicemail access
  • UNKNOWN - Unknown type

Possibility Reasons:

  • IS_POSSIBLE - Number is valid
  • INVALID_COUNTRY_CODE - Invalid country code
  • TOO_SHORT - Too few digits
  • TOO_LONG - Too many digits
  • IS_POSSIBLE_LOCAL_ONLY - Valid locally only
  • INVALID_LENGTH - Invalid length for region

πŸ§ͺ Testing

Run the test suite:

zig build test

πŸ“– Usage Examples

cURL

# Validate a US number
curl -X POST http://localhost:8080/validate \
  -H "Content-Type: application/json" \
  -d '{"phone_number": "+14155552671"}'

# Validate with explicit region
curl -X POST http://localhost:8080/validate \
  -H "Content-Type: application/json" \
  -d '{"phone_number": "4155552671", "region": "US"}'

# International number
curl -X POST http://localhost:8080/validate \
  -H "Content-Type: application/json" \
  -d '{"phone_number": "+442071838750", "region": "GB"}'

Python

import requests

def validate_phone(number: str, region: str = None):
    response = requests.post(
        "http://localhost:8080/validate",
        json={"phone_number": number, "region": region}
    )
    return response.json()

# Example usage
result = validate_phone("+14155552671")
print(f"Valid: {result['valid']}")
print(f"Type: {result['type']}")
print(f"International: {result['international_format']}")

JavaScript/TypeScript

async function validatePhone(
  phoneNumber: string,
  region?: string
): Promise<ValidationResult> {
  const response = await fetch('http://localhost:8080/validate', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ phone_number: phoneNumber, region })
  });
  return response.json();
}

// Example usage
const result = await validatePhone('+14155552671');
console.log(`Valid: ${result.valid}`);
console.log(`Type: ${result.type}`);

πŸ—οΈ Architecture

β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚   Client    β”‚
β”‚ (HTTP/JSON) β”‚
β””β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”˜
       β”‚
       β–Ό
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚   Zig HTTP Server   β”‚
β”‚  - Routing          β”‚
β”‚  - JSON parsing     β”‚
β”‚  - Error handling   β”‚
β””β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
       β”‚ Zero-copy FFI
       β–Ό
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚  C++ Wrapper        β”‚
β”‚  - Type conversion  β”‚
β”‚  - Memory safety    β”‚
β””β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
       β”‚
       β–Ό
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚  libphonenumber     β”‚
β”‚  - Parsing          β”‚
β”‚  - Validation       β”‚
β”‚  - Formatting       β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

🎯 Performance

  • Sub-millisecond validation latency
  • Zero allocation in hot paths (using arena allocators)
  • Concurrent request handling via Zig threads
  • Direct C FFI with no serialization overhead

πŸ”’ Safety

Following Tiger Style principles:

  • βœ… Explicit bounds on all buffers
  • βœ… No recursion
  • βœ… Arena allocators for request scoping
  • βœ… Fail-fast error handling
  • βœ… Comprehensive input validation

🚒 Deployment

Docker

FROM ubuntu:22.04

RUN apt-get update && apt-get install -y \
    libphonenumber-dev libprotobuf-dev libicu-dev

COPY zig-out/bin/phonecheck /usr/local/bin/
EXPOSE 8080
CMD ["phonecheck"]

Systemd Service

[Unit]
Description=PhoneCheck REST API
After=network.target

[Service]
Type=simple
User=phonecheck
ExecStart=/usr/local/bin/phonecheck
Restart=always

[Install]
WantedBy=multi-user.target

πŸ“Š Monitoring

The API exposes structured logs via stdout. Key metrics:

  • Request method and path
  • Response status codes
  • Error messages
  • Connection handling

Integrate with your logging infrastructure (ELK, Loki, CloudWatch, etc.)

🀝 Contributing

  1. Fork the repository
  2. Create a feature branch
  3. Make your changes
  4. Run tests: zig build test
  5. Submit a pull request

πŸ“„ License

MIT License - See LICENSE file

πŸ™ Acknowledgments

  • Google's libphonenumber: The gold standard for phone number handling
  • Zig: Modern systems programming with safety and performance
  • TigerBeetle: Inspiration for robust, zero-technical-debt coding practices

πŸ“ž Support


Built with ❀️ using Zig and libphonenumber

About

High-performance phone number validation REST API built with Zig and Google's libphonenumber. Fast, safe, and production-ready alternative to commercial APIs like Twilio Lookup.

Topics

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published