As developers, we know the value of validating user input quickly and reliably. The phone number is one of the most common and critical pieces of data we handle. An invalid number can break user flows, introduce dirty data into our systems, and waste resources.
This tutorial will provide a clear, step-by-step guide on how to add robust phone number validation and carrier lookup to any application by making a single, simple API call. We'll be using the [Number Verification API], which is a developer favorite for its lightweight JSON responses, millisecond performance, and straightforward documentation.
Step 1: Prerequisites - Get Your API Key
Before you write any code, you'll need an API key to authorize your requests.
- Visit our API Marketplace.
- Sign up for a free account.
- Navigate to your dashboard or "API Keys" section and create a new application to get your unique API Key.
Keep this key handy; you'll need it in the following steps.
Step 2: Understanding the API Endpoint & Data Structure
Let's quickly review the rules of the game before making our first request.
-
API Endpoint Our requests will be sent to the following URL:
https://api.juheapi.com/number-verify/v1/lookup
-
Request Parameters You'll need to pass the following as URL query parameters:
apiKey
: Required. Your unique API key from Step 1.phone
: Required. The phone number you want to validate. For best results, include the country code (e.g.,+14155552671
).
-
Response Structure A successful call will return a standard JSON object. Here is an example of a successful response:
{ "success": true, "valid": true, "country_code": "US", "country_name": "United States of America", "location": "California", "carrier": "AT&T Mobility LLC", "line_type": "mobile" }
success
: Whether the API request itself was processed successfully.valid
: A boolean indicating if the phone number is valid. This is the most important field.carrier
: The number's current mobile carrier.line_type
: The type of line, such asmobile
,landline
, orvoip
.
Step 3: Implementation Walkthrough - Code Examples
Now, let's put theory into practice with some code.
Python Example (for Backend Services)
In your Python backend, the requests
library makes calling the API incredibly simple.
import requests
import json
def verify_phone_number(api_key, phone_number):
"""
Validates a phone number using the Number Verification API.
:param api_key: Your API key.
:param phone_number: The phone number to validate.
:return: The JSON response from the API as a dictionary, or None if an error occurs.
"""
api_url = "https://api.juheapi.com/number-verify/v1/lookup"
params = {
'apiKey': api_key,
'phone': phone_number
}
try:
# Set a timeout to prevent requests from hanging indefinitely
response = requests.get(api_url, params=params, timeout=5)
# Raise an exception for bad status codes (4xx or 5xx)
response.raise_for_status()
data = response.json()
return data
except requests.exceptions.RequestException as e:
print(f"An error occurred while calling the API: {e}")
return None
# --- Example Usage ---
API_KEY = "YOUR_API_KEY" # Replace with your actual API key
phone_to_check = "+14155552671"
validation_result = verify_phone_number(API_KEY, phone_to_check)
if validation_result:
print("API Response:")
print(json.dumps(validation_result, indent=2))
if validation_result.get("valid"):
print(f"\nResult: The number {phone_to_check} is valid.")
print(f"Carrier: {validation_result.get('carrier')}")
else:
print(f"\nResult: The number {phone_to_check} is invalid.")
JavaScript Example (for Web Frontend)
On a webpage, you can use the fetch
API to validate a number in real-time after a user enters it, providing instant feedback.
<!-- Example HTML Structure -->
<label for="phoneInput">Enter phone number:</label>
<input type="text" id="phoneInput" placeholder="+14155552671">
<button onclick="validate()">Validate</button>
<p id="resultMessage"></p>
```javascript
// JavaScript Logic
async function validate() {
const phoneInput = document.getElementById('phoneInput');
const resultMessage = document.getElementById('resultMessage');
const phoneNumber = phoneInput.value;
const apiKey = 'YOUR_API_KEY'; // Replace with your actual API key
if (!phoneNumber) {
resultMessage.textContent = 'Please enter a phone number.';
resultMessage.style.color = 'orange';
return;
}
resultMessage.textContent = 'Validating...';
resultMessage.style.color = 'gray';
const apiUrl = `https://api.juheapi.com/number-verify/v1/lookup?apiKey=${apiKey}&phone=${encodeURIComponent(phoneNumber)}`;
try {
const response = await fetch(apiUrl);
const data = await response.json();
if (response.ok && data.success) {
if (data.valid) {
resultMessage.textContent = `Success! This is a valid number. Carrier: ${data.carrier}.`;
resultMessage.style.color = 'green';
} else {
resultMessage.textContent = 'This is an invalid phone number.';
resultMessage.style.color = 'red';
}
} else {
// Handle API-level errors, e.g., invalid API key
resultMessage.textContent = `Validation failed: ${data.error || 'Unknown error'}`;
resultMessage.style.color = 'red';
}
} catch (error) {
// Handle network errors
console.error('Fetch Error:', error);
resultMessage.textContent = 'Validation request failed. Please check your connection.';
resultMessage.style.color = 'red';
}
}
Step 4: Handling Errors Gracefully
A robust application must handle errors. When calling the API, always consider:
- Network Issues: Use
try...catch
blocks to handle exceptions like network failures. - API Errors: Check the
success
field in the response or the HTTP status code. The API might return specific error messages (e.g., "Invalid API Key," "Usage limit exceeded") that your code should be prepared to handle.
Conclusion & Next Steps
That's it! In just a few steps, you've successfully integrated powerful and reliable phone number validation into your application. This simple addition improves data quality, enhances user experience, and strengthens security.
What's Next?
- Dive into the full API Documentation to explore advanced features like batch validation.
- Join our Developer Community to share what you've built and exchange ideas with other developers!