Python Code to Enhance Zip Codes

This example walks us trough a very simple Python Code that opens a file with a list of zip codes and creates a new CSV file that includes additional details related to the zip code.  You can find this example in the Zip Code github repository

Let's dive right into it.

Pattern:

The first thing we'll do is make sure we have an API Key for using the Zip Code API. You can get a free trial here.  

Code Review

import requests
import csv

We need to use the Python libraries "requests" (to manage API calls) and "csv" to easily manipulate csv files.

vheaders = {"Ocp-Apim-Subscription-Key": ""}

In this section you need to replace the value between the quotes to your API Key. This information is passed in the header section of the REST API call. 

with open(r'sample-zips.txt', 'r') as fp:
with open('zip-enhanced.csv', 'w',newline='') as f:
writer = csv.writer(f)

Using the "with" command we'll open the sample-zips.txt file for "read" and we'll open the file zip-enhanced.csv file for write (note: if the file zip-enhanced.csv exists already, it will be replaced when the code executes).

for line in fp:
vzipcode = line.strip()
url = f"https://global.metadapi.com/zipc/v1/zipcodes/{vzipcode}"
response = requests.get(url,headers=vheaders).json()
csvline = [vzipcode,response["data"]["stateCode"],response["data"]["stateName"],
response["data"]["titleCaseCountyName"],response["data"]["latitude"],response["data"]["longitude"] ]
writer.writerow(csvline)

In this section, we have a loop for each line of the sample-zips.txt, the first step is to assign to the variable vzipcode the current line (minus any special characters for end of line). 
We then build the endpoint to get details of the zip code (the string value of the endpoint in the variable url). 
Next we call the API and assign it to object "response", it's a GET request to the endpoint defined in "url" and we pass the zip code api key in the header. 
We now create a csv line (i.e. comma separated attributes) and we look for specific attributes of the zip code that we need (the state code, the state name, the county of the zip code, the latitude and longitude).  You can see the full schema of the Zip Code response here, there are many other attributes to serve a multitude of needs. 

Get the Zip Code API and start building an awesome solution!


blog comments powered by Disqus

Join our Newsletter

Get the latest information about API products, tutorials and much more. Join now.

    About Our Company

    Metadapi is based in SW Florida.

    Get in touch

    Follow Us