ng-postcode 0.5.4

Validate, parse and format Nigerian postcodes offline: Nigeria's 11-character NIPOST digital postcode (NDAPS). Includes a client for the postcode.gov.ng API.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
//! The NIPOST Postcode API as plain data: requests to send and responses to
//! decode. Nothing here performs I/O, so it works with any HTTP client.
//!
//! Assembly and disassembly are not modelled because [`Postcode`] does both
//! offline.

use std::fmt;

use serde_json::{Map, Value};

use crate::{Postcode, Segment};

pub const BASE_URL: &str = "https://api.postcode.gov.ng";

/// Characters of autocomplete text sent. A full code with its separators is 15.
const MAX_PARTIAL: usize = 64;

/// A GET request whose successful response decodes to `T`.
#[derive(Clone, Debug)]
pub struct Request<T> {
    pub path: &'static str,
    pub query: Vec<(&'static str, String)>,
    read: fn(&Value) -> Option<T>,
}

/// Two requests are equal when they send the same thing.
impl<T> PartialEq for Request<T> {
    fn eq(&self, other: &Self) -> bool {
        self.path == other.path && self.query == other.query
    }
}

#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Coordinate {
    pub lat: f64,
    pub lng: f64,
}

/// Why a request was not built. Nothing is sent.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum InvalidRequest {
    /// The lookup level is outside 1 to 5.
    Level(u8),
    /// The autocomplete text is empty, which the live API never answers.
    EmptyQuery,
    /// The autocomplete text is over 64 characters.
    QueryTooLong,
    /// The named coordinate or distance is not a finite number.
    NotFinite(&'static str),
    /// The named coordinate is off the globe: latitude beyond 90, or longitude beyond 180.
    OutOfRange(&'static str),
    /// The named distance is below zero.
    Negative(&'static str),
}

/// Resolves a postcode. Levels are cumulative from 1 (validity only) to 5,
/// and the API caps the answer at the level granted to the key.
pub fn lookup(code: Postcode, level: u8) -> Result<Request<Lookup>, InvalidRequest> {
    if !(1..=5).contains(&level) {
        return Err(InvalidRequest::Level(level));
    }
    let query = [("code", code.to_string()), ("level", level.to_string())];
    Ok(Request::get("/v1/lookup", query, read_lookup))
}

/// Suggests completions for a partial postcode such as `EK 01 A`.
pub fn autocomplete(partial: &str) -> Result<Request<Autocomplete>, InvalidRequest> {
    if partial.trim().is_empty() {
        return Err(InvalidRequest::EmptyQuery);
    }
    if partial.chars().count() > MAX_PARTIAL {
        return Err(InvalidRequest::QueryTooLong);
    }
    let query = [("q", partial.to_owned())];
    Ok(Request::get(
        "/v1/search/autocomplete",
        query,
        read_autocomplete,
    ))
}

/// Finds the postcode of the nearest building, within 25 m unless
/// `max_distance_m` says otherwise. The API clamps it to 250 m.
pub fn reverse(
    at: Coordinate,
    max_distance_m: Option<f64>,
) -> Result<Request<Reverse>, InvalidRequest> {
    let query = around(at, "max_distance_m", max_distance_m)?;
    Ok(Request::get("/v1/search/reverse", query, read_reverse))
}

/// Lists buildings around a point, nearest first, within 300 m unless
/// `radius_m` says otherwise. Empty when nothing is in range.
pub fn nearby(
    at: Coordinate,
    radius_m: Option<f64>,
) -> Result<Request<Vec<NearbyUnit>>, InvalidRequest> {
    let query = around(at, "radius", radius_m)?;
    Ok(Request::get("/v1/search/nearby", query, read_nearby))
}

fn around(
    at: Coordinate,
    key: &'static str,
    metres: Option<f64>,
) -> Result<Vec<(&'static str, String)>, InvalidRequest> {
    let query = [
        ("lat", Some(at.lat), 90.0),
        ("lng", Some(at.lng), 180.0),
        (key, metres, f64::INFINITY),
    ]
    .into_iter()
    .filter_map(|(key, value, limit)| Some((key, value?, limit)))
    .map(|(key, value, limit)| match value {
        value if !value.is_finite() => Err(InvalidRequest::NotFinite(key)),
        value if value.abs() > limit => Err(InvalidRequest::OutOfRange(key)),
        // Adding zero writes -0.0 as "0", as the other implementations do.
        value => Ok((key, (value + 0.0).to_string())),
    })
    .collect::<Result<_, _>>()?;
    match metres {
        Some(metres) if metres < 0.0 => Err(InvalidRequest::Negative(key)),
        _ => Ok(query),
    }
}

impl<T> Request<T> {
    fn get(
        path: &'static str,
        query: impl IntoIterator<Item = (&'static str, String)>,
        read: fn(&Value) -> Option<T>,
    ) -> Self {
        Self {
            path,
            query: query.into_iter().collect(),
            read,
        }
    }

    /// Decodes the response to this request from its status and body.
    pub fn decode(&self, status: u16, body: &str) -> Result<T, ApiError> {
        let malformed = |reason: &str| ApiError::Malformed {
            status,
            reason: reason.to_owned(),
        };
        let rejected = |code: Option<String>, message: Option<String>| ApiError::Rejected {
            status,
            code: code.unwrap_or_else(|| "unknown_error".to_owned()),
            message: message.unwrap_or_default(),
        };
        // Read as a tree and checked by hand: `data` this version cannot read must not
        // hide the `error` beside it, and keys beside the two are ignored.
        let envelope: Value = serde_json::from_str(body.strip_prefix('\u{feff}').unwrap_or(body))
            .map_err(|error| malformed(&error.to_string()))?;
        if !finite(&envelope) {
            return Err(malformed("number out of range"));
        }
        let envelope = envelope
            .as_object()
            .ok_or_else(|| malformed("expected a JSON object"))?;
        match envelope.get("error") {
            Some(Value::Object(failure)) => {
                return Err(rejected(text(failure, "code"), text(failure, "message")))
            }
            Some(Value::String(message)) => return Err(rejected(None, Some(message.clone()))),
            _ => {}
        }
        if !(200..300).contains(&status) {
            return Err(malformed("an error status without an error"));
        }
        (self.read)(envelope.get("data").unwrap_or(&Value::Null))
            .ok_or_else(|| malformed("unexpected data"))
    }
}

// The readers below are strict about one thing each: the field that carries the
// answer. Any other field of the wrong type is read as absent, so a change NIPOST
// makes to one field cannot fail the whole response.

type Object = Map<String, Value>;

/// serde_json refuses a number no float can hold, unless another crate in the build turns
/// on its `arbitrary_precision` feature. This holds either way.
fn finite(value: &Value) -> bool {
    match value {
        Value::Number(number) => number.as_f64().is_some_and(f64::is_finite),
        Value::Array(items) => items.iter().all(finite),
        Value::Object(fields) => fields.values().all(finite),
        _ => true,
    }
}

fn text(data: &Object, key: &str) -> Option<String> {
    data.get(key)?.as_str().map(str::to_owned)
}

fn number(data: &Object, key: &str) -> Option<f64> {
    data.get(key)?.as_f64()
}

fn object<'a>(data: &'a Object, key: &str) -> Option<&'a Object> {
    data.get(key)?.as_object()
}

/// A unit or suggestion without its code is no answer, so it is dropped.
fn coded(key: &'static str) -> impl Fn(&&Object) -> bool {
    move |item| text(item, key).is_some_and(|code| !code.is_empty())
}

fn raw(data: &Object, key: &str) -> Option<Value> {
    data.get(key).filter(|value| !value.is_null()).cloned()
}

fn read_lookup(data: &Value) -> Option<Lookup> {
    let data = data.as_object()?;
    Some(Lookup {
        postcode: text(data, "postcode").unwrap_or_default(),
        // A body without it is malformed, not an unassigned code.
        valid: data.get("valid")?.as_bool()?,
        administrative_address: object(data, "administrative_address").map(|admin| {
            AdministrativeAddress {
                state_name: text(admin, "state_name"),
                lga_name: text(admin, "lga_name"),
                locality_name: text(admin, "locality_name"),
                zone: text(admin, "zone"),
            }
        }),
        recent_house_address: object(data, "recent_house_address").map(|recent| {
            RecentHouseAddress {
                recent: text(recent, "recent"),
            }
        }),
        building_use_status: text(data, "building_use_status"),
        other_building_info: raw(data, "other_building_info"),
        point_geometry: raw(data, "point_geometry"),
        status: text(data, "status"),
        verified: data.get("verified").and_then(Value::as_bool),
    })
}

fn read_autocomplete(data: &Value) -> Option<Autocomplete> {
    let data = data.as_object()?;
    let suggestions = data.get("suggestions").and_then(Value::as_array);
    Some(Autocomplete {
        // A segment name this version does not know is `None`, not a failed response.
        segment: match data.get("segment").and_then(Value::as_str) {
            Some("state") => Some(Segment::State),
            Some("lga") => Some(Segment::Lga),
            Some("district") => Some(Segment::District),
            Some("area") => Some(Segment::Area),
            Some("unit") => Some(Segment::Unit),
            _ => None,
        },
        suggestions: suggestions
            .into_iter()
            .flatten()
            .filter_map(Value::as_object)
            .filter(coded("code"))
            .map(|item| Suggestion {
                code: text(item, "code").unwrap_or_default(),
                label: text(item, "label"),
            })
            .collect(),
    })
}

fn read_reverse(data: &Value) -> Option<Reverse> {
    let data = data.as_object()?;
    let point = data.get("coordinate").and_then(Value::as_array);
    Some(Reverse {
        // A body without it is malformed, not an empty search.
        found: data.get("found")?.as_bool()?,
        coordinate: point.and_then(|point| match point.as_slice() {
            [lng, lat] => Some(Coordinate {
                lat: lat.as_f64()?,
                lng: lng.as_f64()?,
            }),
            _ => None,
        }),
        unit: object(data, "unit")
            .filter(coded("postcode"))
            .map(|unit| NearestUnit {
                postcode: text(unit, "postcode").unwrap_or_default(),
                display: text(unit, "display").unwrap_or_default(),
                distance_m: number(unit, "distance_m"),
                confidence: text(unit, "confidence"),
                state_name: text(unit, "state_name"),
                lga_name: text(unit, "lga_name"),
                locality_name: text(unit, "locality_name"),
                address: text(unit, "address"),
            }),
        area: text(data, "area"),
        district: text(data, "district"),
        state: text(data, "state"),
        message: text(data, "message"),
        radius_m: number(data, "radius_m"),
        depth: text(data, "depth"),
    })
}

fn read_nearby(data: &Value) -> Option<Vec<NearbyUnit>> {
    let units = data.as_array()?.iter().filter_map(Value::as_object);
    Some(
        units
            .filter(coded("postcode"))
            .map(|unit| NearbyUnit {
                postcode: text(unit, "postcode").unwrap_or_default(),
                display: text(unit, "display").unwrap_or_default(),
                distance_m: number(unit, "distance_m"),
            })
            .collect(),
    )
}

#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum ApiError {
    /// The API refused the request, for example `auth_required` (401),
    /// `insufficient_credits` (402) or a rate limit (429).
    Rejected {
        status: u16,
        code: String,
        message: String,
    },
    /// The body was not the documented JSON envelope.
    Malformed { status: u16, reason: String },
}

impl fmt::Display for ApiError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Rejected {
                status,
                code,
                message,
            } => write!(f, "{code} ({status}): {message}"),
            Self::Malformed { status, reason } => {
                write!(f, "unreadable response ({status}): {reason}")
            }
        }
    }
}

impl std::error::Error for ApiError {}

impl fmt::Display for InvalidRequest {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Level(level) => write!(f, "level must be 1 to 5, got {level}"),
            Self::EmptyQuery => f.write_str("autocomplete text must not be empty"),
            Self::QueryTooLong => {
                write!(f, "autocomplete text is over {MAX_PARTIAL} characters")
            }
            Self::NotFinite(name) => write!(f, "{name} must be a finite number"),
            Self::OutOfRange(name) => write!(f, "{name} is off the globe"),
            Self::Negative(name) => write!(f, "{name} must not be negative"),
        }
    }
}

impl std::error::Error for InvalidRequest {}

/// Fields above the level granted to the key are `None`.
#[derive(Clone, Debug, Default, PartialEq)]
#[non_exhaustive]
pub struct Lookup {
    pub postcode: String,
    /// Required: a body without it is malformed, not an unassigned code.
    pub valid: bool,
    /// Level 2.
    pub administrative_address: Option<AdministrativeAddress>,
    /// Level 2.
    pub recent_house_address: Option<RecentHouseAddress>,
    /// Level 3.
    pub building_use_status: Option<String>,
    /// Level 4. Undocumented, so left untyped.
    pub other_building_info: Option<serde_json::Value>,
    /// Level 5. Undocumented, so left untyped.
    pub point_geometry: Option<serde_json::Value>,
    /// `valid`, `not_found`, or `invalid` for a malformed code. Sent at every level.
    pub status: Option<String>,
    pub verified: Option<bool>,
}

#[derive(Clone, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub struct AdministrativeAddress {
    pub state_name: Option<String>,
    pub lga_name: Option<String>,
    pub locality_name: Option<String>,
    pub zone: Option<String>,
}

#[derive(Clone, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub struct RecentHouseAddress {
    pub recent: Option<String>,
}

#[derive(Clone, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub struct Autocomplete {
    /// The segment the suggestions complete.
    pub segment: Option<Segment>,
    pub suggestions: Vec<Suggestion>,
}

#[derive(Clone, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub struct Suggestion {
    /// The value of the segment being completed, such as `A03`, not a full prefix.
    pub code: String,
    /// Documented by NIPOST but not sent by the live API as of October 2026.
    pub label: Option<String>,
}

#[derive(Clone, Debug, Default, PartialEq)]
#[non_exhaustive]
pub struct Reverse {
    /// Required: a body without it is malformed, not an empty search.
    pub found: bool,
    /// The queried point, echoed back.
    pub coordinate: Option<Coordinate>,
    /// The nearest building, absent when nothing is in range.
    pub unit: Option<NearestUnit>,
    pub area: Option<String>,
    pub district: Option<String>,
    pub state: Option<String>,
    /// Set when nothing is in range.
    pub message: Option<String>,
    /// The radius the API actually applied.
    pub radius_m: Option<f64>,
    /// How deep the match goes, such as `unit`.
    pub depth: Option<String>,
}

#[derive(Clone, Debug, Default, PartialEq)]
#[non_exhaustive]
pub struct NearbyUnit {
    pub postcode: String,
    pub display: String,
    pub distance_m: Option<f64>,
}

#[derive(Clone, Debug, Default, PartialEq)]
#[non_exhaustive]
pub struct NearestUnit {
    pub postcode: String,
    pub display: String,
    pub distance_m: Option<f64>,
    /// `high`, `medium` or `low`, graded by distance.
    pub confidence: Option<String>,
    /// Level 2.
    pub state_name: Option<String>,
    /// Level 2.
    pub lga_name: Option<String>,
    /// Level 2.
    pub locality_name: Option<String>,
    /// Level 2.
    pub address: Option<String>,
}

#[cfg(test)]
mod tests {
    use super::*;

    const HERE: Coordinate = Coordinate {
        lat: 7.62,
        lng: 5.22,
    };

    fn pairs<const N: usize>(query: [(&'static str, &str); N]) -> Vec<(&'static str, String)> {
        query.map(|(key, value)| (key, value.to_owned())).to_vec()
    }

    #[test]
    fn builds_requests() {
        let code: Postcode = "ek01a03fk01".parse().unwrap();
        let request = lookup(code, 3).unwrap();
        assert_eq!(request.path, "/v1/lookup");
        assert_eq!(
            request.query,
            pairs([("code", "EK-01-A03-FK-01"), ("level", "3")])
        );

        assert_eq!(lookup(code, 0), Err(InvalidRequest::Level(0)));
        assert_eq!(autocomplete(" "), Err(InvalidRequest::EmptyQuery));
        let nowhere = Coordinate {
            lat: f64::NAN,
            ..HERE
        };
        assert_eq!(nearby(nowhere, None), Err(InvalidRequest::NotFinite("lat")));

        let request = autocomplete("EK 01 A").unwrap();
        assert_eq!(request.path, "/v1/search/autocomplete");
        assert_eq!(request.query, pairs([("q", "EK 01 A")]));

        let request = reverse(HERE, Some(100.0)).unwrap();
        assert_eq!(request.path, "/v1/search/reverse");
        assert_eq!(
            request.query,
            pairs([("lat", "7.62"), ("lng", "5.22"), ("max_distance_m", "100")])
        );

        let request = nearby(HERE, None).unwrap();
        assert_eq!(request.path, "/v1/search/nearby");
        assert_eq!(request.query, pairs([("lat", "7.62"), ("lng", "5.22")]));
    }

    #[test]
    fn decodes_the_documented_lookup() {
        let body = r#"{ "data": {
            "postcode": "EK-01-A03-FK-01",
            "valid": true,
            "administrative_address": { "state_name": "EKITI", "lga_name": "ADO EKITI", "locality_name": "ADO EKITI", "zone": "SOUTH WEST" },
            "recent_house_address": { "recent": "NTA ROAD, BACK OF FABIAN HOTEL, ADO EKITI" },
            "building_use_status": "residential"
        } }"#;
        let found = lookup("EK-01-A03-FK-01".parse().unwrap(), 3)
            .unwrap()
            .decode(200, body)
            .unwrap();
        assert!(found.valid);
        assert_eq!(
            found.administrative_address.unwrap().zone.as_deref(),
            Some("SOUTH WEST")
        );
        assert_eq!(found.building_use_status.as_deref(), Some("residential"));
        assert_eq!(found.point_geometry, None);
    }

    #[test]
    fn decodes_fields_missing_below_the_granted_level() {
        let body = r#"{ "data": { "postcode": "EK-01-A03-FK-01", "valid": true } }"#;
        let found = lookup("EK-01-A03-FK-01".parse().unwrap(), 1)
            .unwrap()
            .decode(200, body)
            .unwrap();
        assert_eq!(found.administrative_address, None);
    }

    #[test]
    fn decodes_autocomplete_and_reverse() {
        let body = r#"{ "data": { "segment": "lga", "suggestions": [{ "code": "EK-01", "label": "ADO EKITI" }] } }"#;
        let found = autocomplete("EK").unwrap().decode(200, body).unwrap();
        assert_eq!(found.segment, Some(Segment::Lga));
        assert_eq!(found.suggestions[0].code, "EK-01");

        let body = r#"{ "data": { "found": false, "coordinate": [5.22, 7.62], "message": "no unit in range", "radius_m": 25 } }"#;
        let found = reverse(HERE, None).unwrap().decode(200, body).unwrap();
        assert_eq!((found.found, found.unit), (false, None));
        assert_eq!(found.radius_m, Some(25.0));
    }

    #[test]
    fn turns_error_envelopes_and_bad_bodies_into_values() {
        let request = lookup("EK-01-A03-FK-01".parse().unwrap(), 1).unwrap();

        // What the live API answered on 2 October 2026 when called without a key.
        let body = r#"{"error":{"code":"auth_required","message":"an API key is required; pass it in the X-API-Key header"}}"#;
        let expected = ApiError::Rejected {
            status: 401,
            code: "auth_required".to_owned(),
            message: "an API key is required; pass it in the X-API-Key header".to_owned(),
        };
        assert_eq!(request.decode(401, body), Err(expected));

        let malformed = request.decode(502, "<html>Bad Gateway</html>");
        assert!(matches!(
            malformed,
            Err(ApiError::Malformed { status: 502, .. })
        ));
        let empty = request.decode(200, r#"{"data":null}"#);
        assert!(matches!(empty, Err(ApiError::Malformed { .. })));
    }

    #[test]
    fn tolerates_what_the_api_may_add_or_leave_out() {
        let request = lookup("EK-01-A03-FK-01".parse().unwrap(), 1).unwrap();
        let body =
            r#"{"data":{"postcode":"EK-01-A03-FK-01","valid":true},"meta":{"request_id":"r1"}}"#;
        assert!(request.decode(200, body).unwrap().valid);

        let body = r#"{"error":{"code":"rate_limited"},"request_id":"r1"}"#;
        let expected = ApiError::Rejected {
            status: 429,
            code: "rate_limited".to_owned(),
            message: String::new(),
        };
        assert_eq!(request.decode(429, body), Err(expected));

        let body = r#"{"data":{"segment":"street","suggestions":null}}"#;
        let found = autocomplete("EK").unwrap().decode(200, body).unwrap();
        assert_eq!((found.segment, found.suggestions.len()), (None, 0));

        let body = r#"{"data":[{"postcode":null,"distance_m":3}]}"#;
        let units = nearby(HERE, None).unwrap().decode(200, body).unwrap();
        assert_eq!(units, []);

        let body = r#"{"data":{"found":true,"unit":{"postcode":"EK-01-A03-FK-01"}}}"#;
        let found = reverse(HERE, None).unwrap().decode(200, body).unwrap();
        assert_eq!(found.unit.unwrap().distance_m, None);
    }
}