DEV Community

Olly
Olly

Posted on

Flag orders outside your delivery radius with a UK postcode distance check (Python)

Your shop ships from one depot and you want to know which orders fall outside a delivery radius, without paying for a mapping API or loading a postcode database. A UK postcode distance endpoint does it in one call per order.

The call

curl "https://uk-postcodekit-postcode-lookup-nearest-distance.p.rapidapi.com/distance?from=SW1A%201AA&to=M1%201AE" \
  -H "X-RapidAPI-Key: YOUR_KEY" \
  -H "X-RapidAPI-Host: uk-postcodekit-postcode-lookup-nearest-distance.p.rapidapi.com"
Enter fullscreen mode Exit fullscreen mode

Response:

{"distance_km":261.906,"distance_miles":162.741,"from":"SW1A 1AA","note":"Straight-line (great-circle) distance","to":"M1 1AE"}
Enter fullscreen mode Exit fullscreen mode

It is a straight-line distance, so treat it as a quick radius filter, not a driving distance.

The script

import os,requests,sys
BASE=os.environ.get("BASE","https://uk-postcodekit-postcode-lookup-nearest-distance.p.rapidapi.com")
H={"X-RapidAPI-Key":os.environ.get("RAPIDAPI_KEY","YOUR_KEY"),"X-RapidAPI-Host":"uk-postcodekit-postcode-lookup-nearest-distance.p.rapidapi.com"}
def dist(a,b):
    r=requests.get(f"{BASE}/distance",headers=H,params={"from":a,"to":b},timeout=15);r.raise_for_status();return r.json()["distance_miles"]
depot="M1 1AE"
for pc in sys.argv[1:]:
    print(f"{pc:10} {dist(depot,pc):7.1f} miles from depot")
Enter fullscreen mode Exit fullscreen mode

Running it for three customer postcodes:

SW1A 1AA     162.7 miles from depot
LS1 1UR       35.6 miles from depot
EH1 1YZ      174.7 miles from depot
Enter fullscreen mode Exit fullscreen mode

Wiring it in

Wrap dist() in your checkout: reject or surcharge anything over your radius. Use /validate?postcode=... first to catch typos, and /lookup?postcode=... to get the district, ward, latitude and longitude for the order.

Doing it locally

You can download the ONS postcode directory (millions of rows), index it and write the haversine yourself. That is fine at scale, but for a small shop the API is a few lines and no data refresh to maintain.

Limits

The free plan is enough to try this on real orders; paid plans raise the monthly quota. Data is Open Government Licence v3.0 (OS / Royal Mail attribution is returned in /lookup).

UK PostcodeKit on RapidAPI

Top comments (0)