Using Country Codes in REST APIs and GraphQL

Best practices for implementing country codes in APIs. Learn field naming, validation, filtering, and formatting patterns for REST and GraphQL endpoints.

Programming

Detailed Explanation

Country Codes in API Design

Country codes are one of the most common fields in APIs. Getting the format and validation right prevents issues across your entire system.

Choosing a Format

Format Example Use When
Alpha-2 "US" Default choice for most APIs
Alpha-3 "USA" Trade, finance, or human readability needed
Numeric "840" Script-independent systems

Recommendation: Use alpha-2 as the default. It is the most widely recognized, uses the least storage, and matches web standards (BCP 47, ccTLDs, HTML lang).

Field Naming Conventions

{
  "country": "US",
  "country_code": "US",
  "billing_country": "GB",
  "shipping_country_code": "JP",
  "iso_3166_1_alpha2": "DE"
}

Avoid ambiguous names like code or cc. Prefer country_code or country with documentation specifying ISO 3166-1 alpha-2.

Validation

Always validate country codes server-side:

// Simple regex validation
const ALPHA2_REGEX = /^[A-Z]{2}$/;

// Full validation against ISO 3166-1
const VALID_CODES = new Set(['AF', 'AL', 'DZ', /* ... all 249 codes */]);

function validateCountryCode(code) {
  const upper = code.toUpperCase();
  if (!ALPHA2_REGEX.test(upper)) {
    return { valid: false, error: 'Must be exactly 2 uppercase letters' };
  }
  if (!VALID_CODES.has(upper)) {
    return { valid: false, error: 'Not a valid ISO 3166-1 alpha-2 code' };
  }
  return { valid: true };
}

REST API Patterns

Filtering by country:

GET /api/users?country=US
GET /api/products?countries=US,GB,JP

Localized responses:

GET /api/products/123
Accept-Language: ja-JP

{
  "id": 123,
  "name": "Widget",
  "price": { "amount": 1000, "currency": "JPY" },
  "available_countries": ["JP", "US", "GB"]
}

GraphQL Schema

enum CountryCode {
  US
  GB
  JP
  DE
  # ... all 249 codes
}

type Address {
  street: String!
  city: String!
  state: String
  country: CountryCode!
  postalCode: String!
}

type Query {
  users(country: CountryCode): [User!]!
  countries: [Country!]!
}

Error Handling

Return clear error messages when a country code is invalid:

{
  "error": {
    "code": "INVALID_COUNTRY_CODE",
    "message": "The country code 'XX' is not a valid ISO 3166-1 alpha-2 code",
    "field": "shipping_address.country"
  }
}

Use Case

A multi-region SaaS platform uses alpha-2 country codes in its REST API for user profiles, billing addresses, and shipping. The API validates all codes against ISO 3166-1, returns 422 for invalid codes, and uses the country code to determine tax rates, shipping options, and compliance requirements.

Try It — Country Code Reference

Open full tool