sodcalculator

10 Tech How-To

Check Indian PIN Code in Python: Step-by-Step

Guide 10-32384 · Updated · Step by step

This guide shows you how to validate and look up Indian Postal Index Numbers (PIN codes) using Python. You’ll learn to check if a PIN is correctly formatted, fetch location details from a public API, and handle errors gracefully. No prior experience with APIs is needed, just basic Python knowledge.

What You’ll Need

  • Python 3.6 or later installed on your system.
  • An internet connection to access the PIN code API.
  • The requests library. Install it with pip install requests if you haven’t already.

Step-by-Step

  1. Import the required modules. Create a new Python file (e.g., pin_check.py) and start with:
    import requests
  2. Define a function to validate the PIN format. Indian PIN codes are exactly 6 digits, starting with a digit from 1 to 9 (first digit cannot be 0). Use a regex pattern:
    import re
    def is_valid_pin_format(pin):
    return bool(re.fullmatch(r'[1-9][0-9]{5}', pin))
  3. Test the format function. For example, is_valid_pin_format('110001') returns True, is_valid_pin_format('012345') returns False.
  4. Create a function to fetch PIN details from the API. Use the free api.postalpincode.in endpoint. The function will take a PIN string and return the JSON response:
    def get_pin_details(pin):
    url = f"https://api.postalpincode.in/pincode/{pin}"
    response = requests.get(url)
    response.raise_for_status() # raises an error for bad status codes
    return response.json()
  5. Parse the response to extract useful information. The API returns a list with one dictionary. The dictionary has a Status key (“Success” or “Error”) and a PostOffice list (empty if not found). Extract the first post office’s name, district, state, and PIN code:
    def parse_pin_data(data):
    if data[0]['Status'] == 'Success':
    post_office = data[0]['PostOffice'][0]
    return {
    'name': post_office['Name'],
    'district': post_office['District'],
    'state': post_office['State'],
    'pin': post_office['Pincode']
    }
    else:
    return None
  6. Combine everything into a main function. This will validate the format first, then fetch details, and print a user-friendly result:
    def check_pin(pin):
    if not is_valid_pin_format(pin):
    print("Invalid PIN format. Must be 6 digits, first digit not 0.")
    return
    try:
    data = get_pin_details(pin)
    details = parse_pin_data(data)
    if details:
    print(f"PIN {pin} is valid.")
    print(f"Post Office: {details['name']}")
    print(f"District: {details['district']}")
    print(f"State: {details['state']}")
    else:
    print(f"PIN {pin} is not found in the database.")
    except requests.exceptions.RequestException as e:
    print(f"Network or API error: {e}")
  7. Run the function with a test PIN. Add at the bottom of your script:
    if __name__ == "__main__":
    check_pin("110001") # New Delhi GPO
    check_pin("400001") # Mumbai GPO
    check_pin("999999") # Invalid or not found
  8. Execute the script. Run python pin_check.py in your terminal. You should see the details for the valid PINs and an error message for the invalid one.

Common Mistakes

  • Forgetting to install requests: If you get a ModuleNotFoundError, run pip install requests in your terminal.
  • Using a regex that allows 0 as the first digit: Indian PINs cannot start with 0. Use [1-9] as the first character.
  • Not handling API errors: The API might be down or return a non-200 status. Always use response.raise_for_status() or catch exceptions.
  • Assuming the response structure is always the same: The API returns a list, and sometimes the PostOffice list can be empty. Check the status before accessing it.
  • Using a PIN as an integer: If you pass an integer like 110001, the regex will fail because it expects a string. Convert to string first or use str(pin).

Tips

  • Always validate the format locally before making an API call. This saves time and avoids unnecessary requests.
  • Use the requests library’s timeout parameter to avoid hanging if the API is slow: requests.get(url, timeout=5).
  • If you need to check many PINs, consider adding a small delay between requests to be respectful to the free API.
  • You can extend the script to accept user input with input() for interactive use.
  • Store your API calls in a separate function so you can easily mock them in unit tests.

Troubleshooting

Script runs but prints nothing: Check that you have a print statement in your check_pin function. Also ensure you are calling check_pin with a valid argument.

Getting a KeyError when parsing the response: The API response structure might have changed. Print the raw JSON (print(data)) to see the actual keys. Update the parse_pin_data function accordingly.

Network errors (e.g., ConnectionError): Check your internet connection. If you are behind a corporate proxy, you may need to configure the requests session with proxy settings.

API returns Status: "Error" for a valid-looking PIN: This can happen if the PIN is newly created or the API database is not updated. Try a different PIN to confirm the API is working.

Regex matches but the PIN is not found: The format is correct but the PIN doesn’t exist. This is normal—not every 6-digit combination is a valid PIN.

Frequently Asked Questions

Is the API free to use?

Yes, api.postalpincode.in is a free public API with no rate limits documented, but be courteous and avoid heavy usage.

Can I check a PIN without internet?

No, the lookup requires an internet connection. You can only validate the format offline.

What if the PIN is valid but the API returns no data?

This might happen for very new PINs or if the API has a temporary issue. Try again later or use another source.

How do I handle multiple PINs in a list?

Loop through the list and call check_pin for each. Add a small sleep (e.g., time.sleep(0.5)) between calls to avoid overwhelming the API.

Can I use this in a web application?

Yes, you can integrate this logic into a Flask or Django backend to validate PINs on the server side.

Are there any Python packages specifically for this?

There are packages like pincode on PyPI, but they often rely on local data. The API method is more up-to-date.

Related

General steps for current mainstream versions; menus can differ by device and version. See the disclaimer or report an error.

More in this bed

The whole Tech How-To bed →