How to Validate a Postal Code & Get Location Information About it using Java

Cloudmersive
2 min readOct 25, 2022

Looking for a simple & cost-effective way to validate postal codes on your website/app? Our Postal Code Validation API can do the trick. This iteration of our Address Validation API endpoint accepts postal code, country name & country code inputs and returns a ValidPostalCode Boolean in response, along with information about the state/province the postal code is located in (including coordinates). Below, I’ve provided a sample input parse request:

{
"PostalCode": "94566",
"CountryFullName": "United States",
"CountryCode": "string"
}

And its ensuing response:

{
"ValidPostalCode": true,
"City": null,
"StateOrProvince": "California",
"Latitude": 37.65288095,
"Longitude": -121.878627336946
}

Below, I’ll demonstrate how you can take advantage of this API for free using ready-to-run Java code examples provided from our API console page. In addition to these examples, you’ll also need a Cloudmersive API key to authenticate the service (you can get one for free by registering a free account on our website).

Before we get around to calling the API function, our first step is to install the client with Maven. Let’s first add a reference to the pom.xml repository:

<repositories>
<repository>
<id>jitpack.io</id>
<url>https://jitpack.io</url>
</repository>
</repositories>

And let’s next add a reference to the pom.xml dependency:

<dependencies>
<dependency>
<groupId>com.github.Cloudmersive</groupId>
<artifactId>Cloudmersive.APIClient.Java</artifactId>
<version>v4.25</version>
</dependency>
</dependencies>

Next, let’s add our imports to the top of our file and call the function. Once you pass your API key & parse request through the appropriate field, you’re all set:

// Import classes:
//import com.cloudmersive.client.invoker.ApiClient;
//import com.cloudmersive.client.invoker.ApiException;
//import com.cloudmersive.client.invoker.Configuration;
//import com.cloudmersive.client.invoker.auth.*;
//import com.cloudmersive.client.AddressApi;
ApiClient defaultClient = Configuration.getDefaultApiClient();// Configure API key authorization: Apikey
ApiKeyAuth Apikey = (ApiKeyAuth) defaultClient.getAuthentication("Apikey");
Apikey.setApiKey("YOUR API KEY");
// Uncomment the following line to set a prefix for the API key, e.g. "Token" (defaults to null)
//Apikey.setApiKeyPrefix("Token");
AddressApi apiInstance = new AddressApi();
ValidatePostalCodeRequest input = new ValidatePostalCodeRequest(); // ValidatePostalCodeRequest | Input parse request
try {
ValidatePostalCodeResponse result = apiInstance.addressValidatePostalCode(input);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling AddressApi#addressValidatePostalCode");
e.printStackTrace();
}

--

--

Cloudmersive

There’s an API for that. Cloudmersive is a leader in Highly Scalable Cloud APIs.