Backend validation package for CountriesDB - server-side validation for country and subdivision codes
Project description
countriesdb-validator
Backend validation package for CountriesDB. Provides server-side validation for country and subdivision codes using ISO 3166-1 and ISO 3166-2 standards.
📖 Full Documentation | 🌐 Website
Important: This package only provides validation methods. Data fetching for frontend widgets must be done through frontend packages (@countriesdb/widget-core, @countriesdb/widget).
Getting Started
⚠️ API Key Required: This package requires a CountriesDB private API key to function. You must create an account at countriesdb.com to obtain your private API key. Test accounts are available with limited functionality.
- 🔑 Get your API key - Create an account and get your private key
- 📚 View documentation - Complete API reference and examples
- 💬 Support - Get help and support
Installation
pip install countriesdb-validator
Usage
Basic Validation
from validator import CountriesDBValidator
validator = CountriesDBValidator({
"api_key": "YOUR_API_KEY",
})
# Validate a single country
result = validator.validate_country("US")
print(result) # {"valid": True} or {"valid": False, "message": "..."}
# Validate a single subdivision
subdivision_result = validator.validate_subdivision("US-CA", "US")
print(subdivision_result) # {"valid": True} or {"valid": False, "message": "..."}
Multiple Values
# Validate multiple countries
results = validator.validate_countries(["US", "CA", "MX"])
# Returns: [{"code": "US", "valid": True}, {"code": "CA", "valid": True}, ...]
# Validate multiple subdivisions
subdivision_results = validator.validate_subdivisions(
["US-CA", "US-NY", "US-TX"],
"US"
)
# Returns: [{"code": "US-CA", "valid": True}, ...]
Validation Options
# Country validation with follow_upward
result = validator.validate_country("US", follow_upward=True)
# Check if country is referenced in a subdivision
# Subdivision validation with options
result = validator.validate_subdivision(
"US-CA",
"US",
follow_related=True, # Check if subdivision redirects to another country
allow_parent=True # Allow selecting parent subdivisions
)
API Reference
CountriesDBValidator
Main validator class.
Constructor
CountriesDBValidator(config: dict)
Config:
api_key(required): Your CountriesDB API key
Methods
validate_country(code, follow_upward=False)
Validate a single country code.
Parameters:
code(str): ISO 3166-1 alpha-2 country codefollow_upward(bool): Check if country is referenced in a subdivision
Returns: ValidationResult (dict with valid bool and optional message)
validate_countries(codes)
Validate multiple country codes.
Parameters:
codes(List[str]): List of ISO 3166-1 alpha-2 country codes
Returns: List[ValidationResult] (each with code, valid, and optional message)
validate_subdivision(code, country, follow_related=False, allow_parent=False)
Validate a single subdivision code.
Parameters:
code(str | None): Subdivision code (e.g., 'US-CA') or None/empty stringcountry(str): ISO 3166-1 alpha-2 country codefollow_related(bool): Check if subdivision redirects to another countryallow_parent(bool): Allow selecting parent subdivisions
Returns: ValidationResult (dict with valid bool and optional message)
validate_subdivisions(codes, country, allow_parent=False)
Validate multiple subdivision codes.
Parameters:
codes(List[str | None]): List of subdivision codes or None/empty stringscountry(str): ISO 3166-1 alpha-2 country codeallow_parent(bool): Allow selecting parent subdivisions
Returns: List[ValidationResult] (each with code, valid, and optional message)
Examples
Django Validation
from validator import CountriesDBValidator
from django.core.exceptions import ValidationError
validator = CountriesDBValidator({
"api_key": settings.COUNTRIESDB_API_KEY,
})
def validate_user_country(country_code: str, subdivision_code: str = None):
"""Validate user's country and subdivision"""
# Validate country
result = validator.validate_country(country_code)
if not result["valid"]:
raise ValidationError(result["message"])
# Validate subdivision
if subdivision_code:
result = validator.validate_subdivision(subdivision_code, country_code)
if not result["valid"]:
raise ValidationError(result["message"])
Flask Validation
from validator import CountriesDBValidator
from flask import Flask, request, jsonify
app = Flask(__name__)
validator = CountriesDBValidator({
"api_key": os.environ.get("COUNTRIESDB_API_KEY"),
})
@app.route("/api/user", methods=["POST"])
def create_user():
data = request.json
country = data.get("country")
subdivision = data.get("subdivision")
# Validate country
result = validator.validate_country(country)
if not result["valid"]:
return jsonify({"error": result["message"]}), 422
# Validate subdivision
if subdivision:
result = validator.validate_subdivision(subdivision, country)
if not result["valid"]:
return jsonify({"error": result["message"]}), 422
# Proceed with user creation
# ...
return jsonify({"success": True}), 201
FastAPI Validation
from validator import CountriesDBValidator
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
app = FastAPI()
validator = CountriesDBValidator({
"api_key": os.environ.get("COUNTRIESDB_API_KEY"),
})
class UserData(BaseModel):
country: str
subdivision: str | None = None
@app.post("/api/user")
async def create_user(user_data: UserData):
# Validate country
result = validator.validate_country(user_data.country)
if not result["valid"]:
raise HTTPException(status_code=422, detail=result["message"])
# Validate subdivision
if user_data.subdivision:
result = validator.validate_subdivision(
user_data.subdivision,
user_data.country
)
if not result["valid"]:
raise HTTPException(status_code=422, detail=result["message"])
# Proceed with user creation
return {"success": True}
Error Handling
All methods handle network errors and API errors gracefully:
try:
result = validator.validate_country("US")
if not result["valid"]:
print(f"Validation failed: {result['message']}")
except ValueError as e:
print(f"Error: {e}")
Full backend examples
Clone-and-run projects that use this package (and the other SDKs) are available in the CountriesDB examples repository:
javascript/backend-fetch– nativefetchjavascript/backend-axios– axios wrapperjavascript/backend-validator–@countriesdb/validatorpackagejavascript/backend-nextjs– Next.js App Router API routesphp/backend-laravel– PHP/Laravel validation rulesphp/backend-guzzle– vanilla PHP + Guzzlepython/backend-requests– Python requests libraryjava/backend-httpclientandbackend-spring– Java examplescsharp/backend-httpclient– C# .NET examplesgo/backend-http– Go examplesruby/backend-faraday– Ruby examplesbash/backend-curl– Bash cURL examples
Each folder includes a README with setup instructions so you can test the flows end-to-end.
Requirements
- Python 3.8+
requestslibrary
Additional Resources
- 📖 Full Documentation - Complete API reference
- 🌐 Website - Learn more about CountriesDB
- 🔑 Get API Key - Sign up and get your private API key
- 💬 Support - Get help and support
License
PROPRIETARY
Copyright (c) NAYEE LLC. All rights reserved.
This software is the proprietary property of NAYEE LLC. For licensing inquiries, please contact NAYEE LLC.
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file countriesdb_validator-1.0.0.tar.gz.
File metadata
- Download URL: countriesdb_validator-1.0.0.tar.gz
- Upload date:
- Size: 6.5 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.12.3
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
7dfb13b49dba9d5211e20385d18b99d5ff207124a740c985b3572f52bbbff9cb
|
|
| MD5 |
4645857406793f810bc70eb6239cd4f0
|
|
| BLAKE2b-256 |
b558e89670ffe885746ca73bf4da88d85b3f442cffef6a9481692104f5a395e4
|
File details
Details for the file countriesdb_validator-1.0.0-py3-none-any.whl.
File metadata
- Download URL: countriesdb_validator-1.0.0-py3-none-any.whl
- Upload date:
- Size: 7.3 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.12.3
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
dfc60936dceeeaf6f2c21193d0f4a08bbba45cdf1a68eb083d8755235eb0bcb9
|
|
| MD5 |
cf0c17052a138de3284d7bb33899d75f
|
|
| BLAKE2b-256 |
c00b6f7c3d140f3225b644be0b8834520b8a1a85392d881f410fc7f3baa22ea2
|