From 42e586658b4bc39542a5311842f0040f7d29cb2b Mon Sep 17 00:00:00 2001 From: Murilo Ijanc Date: Mon, 27 Jul 2026 20:31:13 -0300 Subject: Name the municipality behind a CEP that does not exist MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The API now hangs an optional faixa block off the 404 of GET /{cep}, and this exposes it as CepNotFoundException.Faixa. A CEP that fails is rarely random: it is usually someone who knows the city and guessed the number, most often the -000 that 957 municipalities never received. Knowing where the guess landed turns a dead-end "CEP not found" into a question worth asking the user. It stays an error. The block names the municipality the number would belong to, never an address, and the lookup still throws. CepIni and CepFim are the smallest and largest CEP that actually exist there, not the range the Correios publish — the published start for Areal is 25845000, exactly the CEP that fails — and the interval between them is sparse, which is what Ceps is for. Parsing is deliberately toothless: absent, misshapen or nameless, the block becomes null and the caller gets the same clean not-found it got before the field existed. A courtesy on top of a 404 must never be able to turn it into a parse failure. --- src/Cepis/CepNotFoundException.cs | 44 +++++++++++++++-- src/Cepis/Cepis.csproj | 2 +- src/Cepis/CepisClient.cs | 70 +++++++++++++++++++++++++-- src/Cepis/Faixa.cs | 99 +++++++++++++++++++++++++++++++++++++++ src/Cepis/FaixaReader.cs | 98 ++++++++++++++++++++++++++++++++++++++ 5 files changed, 305 insertions(+), 8 deletions(-) create mode 100644 src/Cepis/Faixa.cs create mode 100644 src/Cepis/FaixaReader.cs (limited to 'src/Cepis') diff --git a/src/Cepis/CepNotFoundException.cs b/src/Cepis/CepNotFoundException.cs index ced7b16..19a4576 100644 --- a/src/Cepis/CepNotFoundException.cs +++ b/src/Cepis/CepNotFoundException.cs @@ -4,24 +4,60 @@ namespace Cepis; /// The CEP is well-formed but does not exist in the DNE database. /// /// +/// /// Retrying does not help: the answer is definitive until the next fortnightly /// database. A batch never throws this — a CEP with no address is /// at its position instead. +/// +/// +/// carries the municipality the CEP would have belonged to, +/// when the API can name one. It is context for the failure and not a fallback +/// address: this is still a 404. +/// /// public sealed class CepNotFoundException : CepisException { - /// Create the exception with a message. + /// Create the exception with a message and the range, if any. /// what went wrong - public CepNotFoundException(string message) + /// + /// the municipality the CEP would belong to, or when + /// the API named none + /// + public CepNotFoundException(string message, Faixa? faixa = null) : base(message) { + Faixa = faixa; } - /// Create the exception with a message and an underlying cause. + /// Create the exception with a message, the range and a cause. /// what went wrong + /// the municipality the CEP would belong to, if any /// the failure underneath - public CepNotFoundException(string message, Exception? innerException) + public CepNotFoundException(string message, Faixa? faixa, Exception? innerException) : base(message, innerException) { + Faixa = faixa; } + + /// + /// The municipality the CEP would have belonged to, or + /// when there is none. + /// + /// + /// + /// is the ordinary case for a CEP falling in a band + /// no municipality owns: the API omits the block rather than sending + /// a null, and an older API does not send it at all. Anything unreadable in + /// it lands here as too — a courtesy field is not + /// worth turning a clean not-found into a parse error over. + /// + /// + /// It says which municipality the number would be in, not that any + /// address exists. Read before using + /// and : + /// they bound the CEPs that exist there, and the range between them is + /// mostly empty. + /// + /// + public Faixa? Faixa { get; } } diff --git a/src/Cepis/Cepis.csproj b/src/Cepis/Cepis.csproj index 16ffb75..e0ba207 100644 --- a/src/Cepis/Cepis.csproj +++ b/src/Cepis/Cepis.csproj @@ -15,7 +15,7 @@ Cepis - 0.1.0 + 0.2.0 Murilo Ijanc Client for the public CEP API at cep.is. Official Correios data (DNE), refreshed every two weeks. ISC diff --git a/src/Cepis/CepisClient.cs b/src/Cepis/CepisClient.cs index 72637c0..e32b78e 100644 --- a/src/Cepis/CepisClient.cs +++ b/src/Cepis/CepisClient.cs @@ -54,7 +54,7 @@ public sealed class CepisClient : IDisposable public const int MaxBatch = 500; /// The version of this library. - public const string Version = "0.1.0"; + public const string Version = "0.2.0"; private const string AcceptHeader = "application/json, text/csv;q=0.9, */*;q=0.1"; @@ -175,9 +175,17 @@ public sealed class CepisClient : IDisposable /// Look up a single CEP. /// /// + /// /// This is the only call that carries a coordinate. About 57% of CEPs have /// one; when they do not, is /// . + /// + /// + /// A CEP that does not exist throws, as it always has. What is new is that + /// the exception may name the municipality the number would belong to, in + /// — context for the failure, not + /// an address, and never a reason to treat the lookup as having succeeded. + /// /// /// the CEP, masked or not /// cancels the call, waits included @@ -186,7 +194,10 @@ public sealed class CepisClient : IDisposable /// the CEP is not eight digits, in which case no request is made, or the API /// rejected it with a 400 /// - /// well-formed, but not in the database + /// + /// well-formed, but not in the database; carries the municipality it would + /// belong to when the API names one + /// /// the API answered 429 on every attempt /// the API answered 5xx on every attempt /// the request never completed @@ -198,7 +209,8 @@ public sealed class CepisClient : IDisposable if (reply.Status == 404) { - throw new CepNotFoundException($"CEP {number} does not exist in the DNE database"); + var faixa = ReadFaixa(reply.Body); + throw new CepNotFoundException(NotFoundMessage(number, faixa), faixa); } if (reply.Status == 400) @@ -459,6 +471,58 @@ public sealed class CepisClient : IDisposable return fallback; } + /// + /// Read the faixa block out of a 404 body, when it has one. + /// + /// + /// The block is optional and always will be: the API omits it — it does not + /// send a null — for a CEP in a band no municipality owns. Absent, + /// misshapen or unreadable, the answer here is and + /// the caller still gets the plain not-found it was going to get anyway. + /// + /// the 404 body + /// the municipality the CEP would belong to, or null + private static Faixa? ReadFaixa(byte[] body) + { + try + { + using var document = JsonDocument.Parse(new ReadOnlyMemory(body)); + if (document.RootElement.ValueKind == JsonValueKind.Object + && document.RootElement.TryGetProperty("faixa", out var faixa)) + { + return FaixaReader.Read(faixa); + } + } + catch (JsonException) + { + return null; + } + + return null; + } + + /// + /// What to tell the caller about a CEP that is not in the database. + /// + /// + /// The municipality goes in the message when the API named one, because the + /// message is what ends up in a log, and "the range belongs to Areal/RJ" is + /// the difference between a dead end and a question worth asking the user. + /// The count is in it for the same reason the API sends it: so nobody reads + /// the two ends as a list of CEPs to walk. + /// + /// the eight digits + /// the municipality it would belong to, if any + /// the message + private static string NotFoundMessage(string cep, Faixa? faixa) + { + var message = $"CEP {cep} does not exist in the DNE database"; + return faixa is null + ? message + : message + $" — the range belongs to {faixa.Localidade}/{faixa.UF}, " + + $"which has {faixa.Ceps} CEP(s) between {faixa.CepIni} and {faixa.CepFim}"; + } + private static string Preview(byte[] body) => Encoding.UTF8.GetString(body, 0, Math.Min(body.Length, 120)); diff --git a/src/Cepis/Faixa.cs b/src/Cepis/Faixa.cs new file mode 100644 index 0000000..e2477b6 --- /dev/null +++ b/src/Cepis/Faixa.cs @@ -0,0 +1,99 @@ +using System.Text.Json.Serialization; + +namespace Cepis; + +/// +/// The municipality a CEP that does not exist would have belonged to. +/// +/// +/// +/// This is context for an error, never an address. It rides on the 404 +/// of , hanging +/// off . The CEP that was asked for +/// still does not exist, and nothing here says otherwise: filling a form from +/// these fields would be inventing an address. +/// +/// +/// It is worth having because a CEP that fails is rarely random — it is usually +/// someone who knows the city and guessed the number. The classic guess is the +/// -000, which 957 municipalities never received. Knowing where the +/// guess landed is what turns "CEP not found" into "did you mean a street in +/// Areal/RJ?". +/// +/// +/// and are the smallest and the +/// largest CEP that actually exist in that municipality, not the +/// bounds the Correios publish. For Areal the DNE's own range starts at +/// 25845000 — exactly the CEP that just failed — while +/// is 25845001. +/// +/// +/// The range is sparse, and the pair is not a list of valid CEPs. Areal +/// has 118 of them () spread across the ~4,900 numbers +/// between its two ends, so a number picked in between overwhelmingly does not +/// exist either. Never iterate the interval, and never show it as a set of +/// usable CEPs. +/// +/// +/// The property names are the API's own, in Portuguese, with only the casing +/// adapted — the same rule the rest of the data follows. On the wire they are +/// localidade, uf, estado, regiao, ibge, +/// cep_ini, cep_fim and ceps. +/// +/// +public sealed record Faixa +{ + /// The municipality. Wire name localidade. + [JsonPropertyName("localidade")] + public string Localidade { get; init; } = ""; + + /// The two-letter state code. Wire name uf. + [JsonPropertyName("uf")] + public string UF { get; init; } = ""; + + /// The state's name. Wire name estado. + [JsonPropertyName("estado")] + public string Estado { get; init; } = ""; + + /// The region of the country. Wire name regiao. + [JsonPropertyName("regiao")] + public string Regiao { get; init; } = ""; + + /// The IBGE municipality code. Wire name ibge. + [JsonPropertyName("ibge")] + public string Ibge { get; init; } = ""; + + /// + /// The smallest CEP that exists in that municipality, unmasked. Wire name + /// cep_ini. + /// + /// + /// The smallest one in the database, not the start of the range the + /// Correios publish — the published start may itself be a CEP that was never + /// issued, which is often precisely the one the caller just tried. + /// + [JsonPropertyName("cep_ini")] + public string CepIni { get; init; } = ""; + + /// + /// The largest CEP that exists in that municipality, unmasked. Wire name + /// cep_fim. + /// + /// + /// Together with it bounds the CEPs of the + /// municipality; it does not enumerate them. See . + /// + [JsonPropertyName("cep_fim")] + public string CepFim { get; init; } = ""; + + /// + /// How many CEPs the municipality actually has. Wire name ceps. + /// + /// + /// This field exists to keep and + /// from being read as a contiguous interval. Areal's 118 CEPs sit inside a + /// span of about 4,900 numbers: the range is mostly empty. + /// + [JsonPropertyName("ceps")] + public int Ceps { get; init; } +} diff --git a/src/Cepis/FaixaReader.cs b/src/Cepis/FaixaReader.cs new file mode 100644 index 0000000..da3c6a2 --- /dev/null +++ b/src/Cepis/FaixaReader.cs @@ -0,0 +1,98 @@ +using System.Globalization; +using System.Text.Json; + +namespace Cepis; + +/// +/// Reads the faixa block of a 404 body, yielding +/// for anything it cannot make sense of. +/// +/// +/// +/// A reader rather than a +/// because faixa is not a field of any model this library deserializes: +/// it hangs off an error body that is otherwise only read for its message. +/// +/// +/// Nothing in here throws. The block is a courtesy on top of a 404 — a missing, +/// misshapen or half-empty one must leave the caller with the same clean +/// it would have got before the API grew the +/// field, never with a parse failure on top of a not-found. +/// +/// +internal static class FaixaReader +{ + /// Turn the faixa element into a range, or null. + /// the block, as it came off the wire + /// the range, or null when there is nothing usable in it + internal static Faixa? Read(JsonElement element) + { + if (element.ValueKind != JsonValueKind.Object) + { + return null; + } + + var localidade = ReadString(element, "localidade"); + if (string.IsNullOrWhiteSpace(localidade)) + { + return null; + } + + return new Faixa + { + Localidade = localidade, + UF = ReadString(element, "uf"), + Estado = ReadString(element, "estado"), + Regiao = ReadString(element, "regiao"), + Ibge = ReadString(element, "ibge"), + CepIni = ReadString(element, "cep_ini"), + CepFim = ReadString(element, "cep_fim"), + Ceps = ReadInt(element, "ceps"), + }; + } + + /// + /// The property as text, or the empty string when it is absent or of a + /// shape that is not text. + /// + /// + /// A number is accepted and taken verbatim, the way + /// does it for the address fields. + /// + private static string ReadString(JsonElement owner, string name) + { + if (!owner.TryGetProperty(name, out var element)) + { + return ""; + } + + return element.ValueKind switch + { + JsonValueKind.String => element.GetString() ?? "", + JsonValueKind.Number => element.GetRawText(), + _ => "", + }; + } + + /// The property as a count, or zero when it cannot be read. + private static int ReadInt(JsonElement owner, string name) + { + if (!owner.TryGetProperty(name, out var element)) + { + return 0; + } + + return element.ValueKind switch + { + JsonValueKind.Number => element.TryGetInt32(out var number) ? number : 0, + JsonValueKind.String => int.TryParse( + element.GetString(), + NumberStyles.Integer, + CultureInfo.InvariantCulture, + out var parsed) + ? parsed + : 0, + _ => 0, + }; + } +} -- cgit v1.3