- C#
- Python
- NodeJS
Name Validation 3 C# Code Snippet
using System.Text.Json;
namespace name_validation_3_dot_net.REST
{
/// <summary>
/// Provides functionality to call the ServiceObjects Name Validation 3 (NV3) REST API's ValidateName endpoint.
/// </summary>
public class ValidateNameClient
{
private const string LiveBaseUrl = "https://sws.serviceobjects.com/NV3/";
private const string BackupBaseUrl = "https://swsbackup.serviceobjects.com/NV3/";
private const string TrialBaseUrl = "https://trial.serviceobjects.com/NV3/";
/// <summary>
/// Synchronously calls the ValidateName REST endpoint to retrieve name validation information.
/// </summary>
/// <param name="input">The input parameters including name components, options, and authentication ID.</param>
/// <returns>Deserialized <see cref="ValidateNameResponse"/> containing either nameResult or statusDetail.</returns>
public static ValidateNameResponse Invoke(ValidateNameInput input)
{
string url = BuildUrl(input, input.IsLive ? LiveBaseUrl : TrialBaseUrl);
string jsonResponse = Helper.HttpGet(url, input.TimeoutSeconds);
ValidateNameResponse response = DeserializeValidateNameResponse(jsonResponse);
if (input.IsLive && response.NameResult == null && response.StatusDetail == null)
{
string fallbackUrl = BuildUrl(input, BackupBaseUrl);
string fallbackJsonResponse = Helper.HttpGet(fallbackUrl, input.TimeoutSeconds);
response = DeserializeValidateNameResponse(fallbackJsonResponse);
}
return response;
}
/// <summary>
/// Asynchronously calls the ValidateName REST endpoint to retrieve name validation information.
/// </summary>
/// <param name="input">The input parameters including name components, options, and authentication ID.</param>
/// <returns>Deserialized <see cref="ValidateNameResponse"/> containing either nameResult or statusDetail.</returns>
public static async Task<ValidateNameResponse> InvokeAsync(ValidateNameInput input)
{
string url = BuildUrl(input, input.IsLive ? LiveBaseUrl : TrialBaseUrl);
string jsonResponse = await Helper.HttpGetAsync(url, input.TimeoutSeconds).ConfigureAwait(false);
ValidateNameResponse response = DeserializeValidateNameResponse(jsonResponse);
if (input.IsLive && response.NameResult == null && response.StatusDetail == null)
{
string fallbackUrl = BuildUrl(input, BackupBaseUrl);
string fallbackJsonResponse = await Helper.HttpGetAsync(fallbackUrl, input.TimeoutSeconds).ConfigureAwait(false);
response = DeserializeValidateNameResponse(fallbackJsonResponse);
}
return response;
}
private static ValidateNameResponse DeserializeValidateNameResponse(string jsonResponse)
{
var options = new JsonSerializerOptions
{
PropertyNameCaseInsensitive = true
};
ValidateNameResponse? response =
JsonSerializer.Deserialize<ValidateNameResponse>(jsonResponse, options);
if (response == null)
{
throw new Exception("Failed to deserialize ValidateName response.");
}
if (response.NameResult == null && response.StatusDetail == null)
{
throw new Exception("Unknown response format from ValidateName API.");
}
return response;
}
public static string BuildUrl(ValidateNameInput input, string baseUrl)
{
string qs = $"ValidateName?" +
$"FullName={Helper.UrlEncode(input.FullName)}" +
$"&Prefix={Helper.UrlEncode(input.Prefix)}" +
$"&FirstName={Helper.UrlEncode(input.FirstName)}" +
$"&MiddleName={Helper.UrlEncode(input.MiddleName)}" +
$"&LastName={Helper.UrlEncode(input.LastName)}" +
$"&Suffix={Helper.UrlEncode(input.Suffix)}" +
$"&Options={Helper.UrlEncode(input.Options)}" +
$"&AuthID={Helper.UrlEncode(input.AuthID)}";
return baseUrl + qs;
}
/// <summary>
/// Input parameters for the ValidateName API call. Represents a name to validate.
/// </summary>
/// <param name="FullName">The full name to validate.</param>
/// <param name="Prefix">The prefix of the name.</param>
/// <param name="FirstName">The first name.</param>
/// <param name="MiddleName">The middle name.</param>
/// <param name="LastName">The last name.</param>
/// <param name="Suffix">The suffix of the name.</param>
/// <param name="Options">Comma-separated list of optional parameters.</param>
/// <param name="AuthID">The authentication ID provided by Service Objects.</param>
/// <param name="IsLive">Indicates whether to use the live service or trial service.</param>
/// <param name="TimeoutSeconds">Timeout duration for the API call, in seconds.</param>
public record ValidateNameInput(
string FullName = "",
string Prefix = "",
string FirstName = "",
string MiddleName = "",
string LastName = "",
string Suffix = "",
string Options = "",
string AuthID = "",
bool IsLive = true,
int TimeoutSeconds = 15
);
}
}
using System;
using System.Collections.Generic;
using System.IO;
using System.Net.Http;
using System.Reflection;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
using System.Web;
namespace name_validation_3_dot_net.REST
{
public static class Helper
{
private static readonly HttpClient _client = new HttpClient();
public static async Task<string> HttpGetAsync(string url, int timeoutSeconds)
{
_client.Timeout = TimeSpan.FromSeconds(timeoutSeconds);
HttpResponseMessage response = await _client.GetAsync(url).ConfigureAwait(false);
string jsonResponse = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
return jsonResponse;
}
public static string HttpGet(string url, int timeoutSeconds)
{
_client.Timeout = TimeSpan.FromSeconds(timeoutSeconds);
HttpResponseMessage response = _client.GetAsync(url).GetAwaiter().GetResult();
string jsonResponse = response.Content.ReadAsStringAsync().GetAwaiter().GetResult();
return jsonResponse;
}
public static string UrlEncode(string value) => HttpUtility.UrlEncode(value ?? string.Empty);
}
}
Name Validation 3 Python Code Snippet
from nv3_response import NV3Response, NameResult, StatusDetail
import requests
import json
# Endpoint URLs for Service Objects Name Validation 3 (NV3) API
primary_url = "https://sws.serviceobjects.com/NV3/ValidateName?"
backup_url = "https://swsbackup.serviceobjects.com/NV3/ValidateName?"
trial_url = "https://trial.serviceobjects.com/NV3/ValidateName?"
def validate_name(
full_name: str = "",
prefix: str = "",
first_name: str = "",
middle_name: str = "",
last_name: str = "",
suffix: str = "",
auth_id: str = "",
is_live: bool = True,
timeout_seconds: int = 15
) -> NV3Response:
"""
Validates a name using the Service Objects Name Validation 3 (NV3) API. NV3 uses machine learning to
to assess and classify input names. Will validate and score, as well as analyze for negative sentiment
and classify the input to distinguish between names and other types of inputs like business, dictionary, or garbage.
Returns a StatusDetails response if invalid.
Args:
full_name (str, optional): The full name to validate. Required if no other name inputs are provided.
prefix (str, optional): The name prefix (e.g., "Dr.", "Mr.").
first_name (str, optional): The first name.
middle_name (str, optional): The middle name.
last_name (str, optional): The last name.
suffix (str, optional): The name suffix (e.g., "Jr.", "III").
auth_id (str): Your Service Objects authentication ID.
is_live (bool, optional): Whether to use the live endpoint or the trial endpoint. Defaults to True (live).
timeout_seconds (int, optional): Timeout for the API request in seconds.
Returns:
NV3Response: Parsed JSON response with name details or a StatusDetails if validation fails or the API call fails.
Raises:
RuntimeError: If the API call fails with a status of "500".
requests.RequestException: On network/HTTP failures (trial mode).
"""
params = {
"FullName": full_name,
"Prefix": prefix,
"FirstName": first_name,
"MiddleName": middle_name,
"LastName": last_name,
"Suffix": suffix,
"AuthID": auth_id
}
url = primary_url if is_live else trial_url
try:
response = requests.get(url, params=params, timeout=timeout_seconds)
response.raise_for_status()
response_data = response.json()
status_details = response_data.get("StatusDetail")
if status_details:
if is_live:
#Try backup
response = requests.get(backup_url, params=params, timeout=timeout_seconds)
response.raise_for_status()
status_details = response.json().get("StatusDetail")
if status_details:
return NV3Response(StatusDetails=StatusDetail(**status_details))
else:
return NV3Response(StatusDetails=StatusDetail(**status_details))
name_result = response_data.get("nameResult") or {}
status_detail = response_data.get("statusDetail")
return NV3Response(
Status=response_data.get("status"),
NameResult=NameResult(
IsValidName=name_result.get("isValidName"),
Classification=name_result.get("classification"),
Confidence=name_result.get("confidence"),
TextIn=name_result.get("textIn"),
TextOut=name_result.get("textOut"),
ParsedName=name_result.get("parsedName"),
PossibleNames=name_result.get("possibleNames"),
Notes=name_result.get("notes"),
Warnings=name_result.get("warnings"),
FirstNameFound=name_result.get("firstNameFound"),
IsCommonFirstName=name_result.get("isCommonFirstName"),
LastNameFound=name_result.get("lastNameFound"),
IsCommonLastName=name_result.get("isCommonLastName"),
SimilarFirstNames=name_result.get("similarFirstNames"),
SimilarLastNames=name_result.get("similarLastNames"),
RelatedNames=name_result.get("relatedNames"),
),
StatusDetail=StatusDetail(
Message=status_detail.get("message"),
Detail=status_detail.get("detail"),
) if status_detail else None
)
except requests.RequestException as req_exc:
if is_live:
#Try backup
try:
response = requests.get(backup_url, params=params, timeout=timeout_seconds)
response.raise_for_status()
response_data = response.json()
return NV3Response(
Status=response_data.get("status"),
NameResult=NameResult(
IsValidName=name_result.get("isValidName"),
Classification=name_result.get("classification"),
Confidence=name_result.get("confidence"),
TextIn=name_result.get("textIn"),
TextOut=name_result.get("textOut"),
ParsedName=name_result.get("parsedName"),
PossibleNames=name_result.get("possibleNames"),
Notes=name_result.get("notes"),
Warnings=name_result.get("warnings"),
FirstNameFound=name_result.get("firstNameFound"),
IsCommonFirstName=name_result.get("isCommonFirstName"),
LastNameFound=name_result.get("lastNameFound"),
IsCommonLastName=name_result.get("isCommonLastName"),
SimilarFirstNames=name_result.get("similarFirstNames"),
SimilarLastNames=name_result.get("similarLastNames"),
RelatedNames=name_result.get("relatedNames"),
),
StatusDetail=StatusDetail(
Message=status_detail.get("message"),
Detail=status_detail.get("detail"),
) if status_detail else None
)
except requests.RequestException as backup_exc:
raise RuntimeError(f"API call failed for both primary and backup endpoints: {backup_exc}") from backup_exc
"""
Response classes for Name Validation 3 (NV3) API
"""
from dataclasses import dataclass
from typing import List, Optional
@dataclass
class StatusDetail:
Message: Optional[str] = None
Detail: Optional[str] = None
def __str__(self):
return f"StatusDetail(Message={self.Message}, Detail={self.Detail})"
@dataclass
class NV3Response:
Status: Optional[str] = None
NameResult: Optional[NameResult] = None
StatusDetail: Optional[StatusDetail] = None
def __str__(self):
return (f"NV3Response(Status={self.Status}, NameResult={self.NameResult}, "
f"StatusDetail={self.StatusDetail})")
@dataclass
class NameResult:
IsValidName: Optional[bool] = None
Classification: Optional[str] = None
Confidence: Optional[float] = None
TextIn: Optional[str] = None
TextOut: Optional[str] = None
ParsedName: Optional[ParsedName] = None
PossibleNames: Optional[List['PossibleName']] = None
Notes: Optional[str] = None
Warnings: Optional[str] = None
FirstNameFound: Optional[bool] = None
IsCommonFirstName: Optional[bool] = None
LastNameFound: Optional[bool] = None
IsCommonLastName: Optional[bool] = None
SimilarFirstNames: Optional[List[str]] = None
SimilarLastNames: Optional[List[str]] = None
RelatedNames: Optional[List[str]] = None
def __post_init__(self):
if self.PossibleNames is None:
self.PossibleNames = []
if self.SimilarFirstNames is None:
self.SimilarFirstNames = []
if self.SimilarLastNames is None:
self.SimilarLastNames = []
if self.RelatedNames is None:
self.RelatedNames = []
def __str__(self):
possible_names_str = "\n".join(str(name) for name in self.PossibleNames) if self.PossibleNames else "None"
return (f"NameResult(Confidence={self.Confidence}, TextIn='{self.TextIn}', TextOut='{self.TextOut}', "
f"PossibleNames=[{possible_names_str}], Notes='{self.Notes}', Warnings='{self.Warnings}', "
f"FirstNameFound={self.FirstNameFound}, IsCommonFirstName={self.IsCommonFirstName}, "
f"LastNameFound={self.LastNameFound}, IsCommonLastName={self.IsCommonLastName}, "
f"SimilarFirstNames={self.SimilarFirstNames}, SimilarLastNames={self.SimilarLastNames}, "
f"RelatedNames={self.RelatedNames})")
@dataclass
class ParsedName:
Prefix: Optional[str] = None
First: Optional[str] = None
Middle: Optional[str] = None
Last: Optional[str] = None
Suffix: Optional[str] = None
def __str__(self):
return (f"ParsedName(Prefix='{self.Prefix}', First='{self.First}', Middle='{self.Middle}', "
f"Last='{self.Last}', Suffix='{self.Suffix}')")
@dataclass
class PossibleName:
Confidence: Optional[float] = None
ParsedName: Optional[ParsedName] = None
def __str__(self):
return f"PossibleName(Confidence={self.Confidence}, ParsedName={self.ParsedName})"
Name Validation 3 NodeJS Code Snippet
import axios from 'axios';
import queryString from 'querystring';
import { NV3Response, NameResult, StatusDetail } from './nv3_response.js';
/**
* @constant
* @type {string}
* @description Base URL for the live Service Objects Name Validation 3 (NV3) API service.
*/
const liveBaseUrl = 'https://sws.serviceobjects.com/NV3/';
/**
* @constant
* @type {string}
* @description Base URL for the backup Service Objects Name Validation 3 (NV3) API service.
*/
const backupBaseUrl = 'https://swsbackup.serviceobjects.com/NV3/';
/**
* @constant
* @type {string}
* @description Trial URL for the backup Service Objects Name Validation 3 (NV3) API service.
*/
const trialBaseUrl = 'https://trial.serviceobjects.com/NV3/';
/**
* Checks if a response from the API is valid by verifying that it has no StatusDetail object
* @param {NV3Response} response - The response object to check
* @returns {boolean} - True if the response is valid, false otherwise
*/
const isValid = (response) => !response?.NameResult !==null;
/**
* Constructs the full API URL by combining the base URL and URL-encoded query string parameters
* derived from the input parameters.
* @param {string} baseUrl - The base URL for the API endpoint (live, backup, or trial)
* @param {Object} params - The query parameters for the API request
* @returns {string} - The full API URL
*/
const buildUrl = (baseUrl, params) =>
`${baseUrl}ValidateName?${queryString.stringify(params)}`;
/**
* Performs an HTTP GET request to the specified URL with a given timeout.
* @param {string} url - The URL to send the GET request to
* @param {number} timeoutSeconds - The timeout for the request in seconds
* @returns {Promise<NV3Response>} - A promise that resolves to an NV3Response object containing the API response data
* @throws {Error} - Throws an error if the request fails
*/
export const httpGet = async (url, timeoutSeconds) => {
let result = new NV3Response();
try {
const response = await axios.get(url, { timeout: timeoutSeconds * 1000 });
if (response.status === 200) {
result.Status = response.data.status ?? null;
result.NameResult = response.data.nameResult ? new NameResult(response.data.nameResult) : null;
result.StatusDetail = response.data.statusDetail ? new StatusDetail(response.data.statusDetail) : null;
}
else {
result.Status = null;
result.NameResult = null;
result.StatusDetail = null;
}
} catch (error) {
throw new Error(`HTTP GET request failed: ${error.message}`);
}
return result;
};
const ValidateNameClient = {
/**
* Provides functionality to call the Service Objects Name Validation 3 (NV3) API's ValidateName endpoint,
* retrieving name validation and classification details for a given name. Includes fallback to backup
* endpoint for reliability in live mode.
* @param {string} [FullName] - The full name to validate. Optional to use instead of individual name components.
* @param {string} [Prefix] - The name prefix to validate. Optional.
* @param {string} [FirstName] - The first name to validate. Optional if FullName is provided.
* @param {string} [MiddleName] - The middle name to validate. Optional.
* @param {string} [LastName] - The last name to validate. Optional if FullName is provided.
* @param {string} [Suffix] - The name suffix to validate. Optional.
* @param {string} [Options] - Additional options for the API request. Optional.
* @param {string} AuthID - The license key for authenticating with the API. Required.
* @param {boolean} [isLive=true] - Whether to use the live API endpoint (true) or the trial endpoint (false).
* @param {number} [timeoutSeconds=15] - The timeout for the API request in seconds. Optional, defaults to 15 seconds.
* @returns {Promise<NV3Response>} A promise that resolves to a NV3Response object.
*/
async invokeAsync(FullName, Prefix, FirstName, MiddleName, LastName, Suffix, Options, AuthID, isLive = true, timeoutSeconds = 15) {
const params = {
FullName,
Prefix,
FirstName,
MiddleName,
LastName,
Suffix,
Options,
AuthID
};
const url = buildUrl(isLive ? liveBaseUrl : trialBaseUrl, params);
let response = await httpGet(url, timeoutSeconds);
if (isLive && !isValid(response)) {
const fallbackUrl = buildUrl(backupBaseUrl, params);
const fallbackResponse = await httpGet(fallbackUrl, timeoutSeconds);
return fallbackResponse;
}
return response;
},
/**
* Synchronously invokes the ValidateName API endpoint by wrapping the async call
* and awaiting its result immediately. Note: This method should be used cautiously
* in Node.js as it blocks the event loop.
* @param {string} [FullName] - The full name to validate. Optional to use instead of individual name components.
* @param {string} [Prefix] - The name prefix to validate. Optional.
* @param {string} [FirstName] - The first name to validate. Optional if FullName is provided.
* @param {string} [MiddleName] - The middle name to validate. Optional.
* @param {string} [LastName] - The last name to validate. Optional if FullName is provided.
* @param {string} [Suffix] - The name suffix to validate. Optional.
* @param {string} [Options] - Additional options for the API request. Optional.
* @param {string} AuthID - The license key for authenticating with the API. Required.
* @param {boolean} [isLive=true] - Whether to use the live API endpoint (true) or the trial endpoint (false).
* @param {number} [timeoutSeconds=15] - The timeout for the API request in seconds. Optional, defaults to 15 seconds.
* @returns {NV3Response} - The response from the API call
*/
invoke(FullName, Prefix, FirstName, MiddleName, LastName, Suffix, Options, AuthID, isLive = true, timeoutSeconds = 15) {
return (async () => await this.invokeAsync(
FullName, Prefix, FirstName, MiddleName, LastName, Suffix, Options, AuthID, isLive, timeoutSeconds
))();
}
};
export { ValidateNameClient, NV3Response };
/**
* Validate name response component for NV3 API
*/
export class NV3Response {
constructor(data = {}) {
this.Status = data.status ?? null;
this.NameResult = data.nameResult ? new NameResult(data.nameResult) : null;
this.StatusDetail = data.statusDetail ? new StatusDetail(data.statusDetail) : null;
}
get IsSuccess() {
return this.NameResult !== null;
}
}
/**
* NameResult component for NV3 API response
*/
export class NameResult {
constructor(data = {}) {
this.IsValidName = data.isValidName ?? null;
this.Classification = data.classification ?? null;
this.Confidence = data.confidence ?? null;
this.TextIn = data.textIn ?? null;
this.TextOut = data.textOut ?? null;
this.ParsedName = data.parsedName ? new ParsedName(data.parsedName) : null;
this.PossibleNames = Array.isArray(data.possibleNames)
? data.possibleNames.map(name => new NameInfo(name))
: [];
this.Notes = data.notes ?? null;
this.Warnings = data.warnings ?? null;
this.FirstNameFound = data.firstNameFound ?? null;
this.IsCommonFirstName = data.isCommonFirstName ?? null;
this.LastNameFound = data.lastNameFound ?? null;
this.IsCommonLastName = data.isCommonLastName ?? null;
this.SimilarFirstNames = data.similarFirstNames ?? null;
this.SimilarLastNames = data.similarLastNames ?? null;
this.RelatedNames = data.relatedNames ?? null;
}
}
/**
* ParsedName component for NV3 API response
*/
export class ParsedName {
constructor(data = {}) {
this.Prefix = data.prefix ?? null;
this.First = data.first ?? null;
this.Middle = data.middle ?? null;
this.Last = data.last ?? null;
this.Suffix = data.suffix ?? null;
}
}
/**
* NameInfo component for possibleNames
*/
export class NameInfo {
constructor(data = {}) {
this.Confidence = data.confidence ?? null;
this.ParsedName = data.parsedName ? new ParsedName(data.parsedName) : null;
}
}
/**
* StatusDetail component for NV3 API errors
*/
export class StatusDetail {
constructor(data = {}) {
this.Message = data.message ?? null;
this.Detail = data.detail ?? null;
}
}