/municipios-api

Simple Flask API for getting distance and adjacency information on Puerto Rico's municipalities

Primary LanguagePythonMIT LicenseMIT

What

This is source code for generating a graph representation of Puerto Rico municipalities as well as for running a Flask API that can retrieve useful data from the graph.

Where

You can use the API at municipios.rauln.com. There are two endpoints: /distance and /adjacent. The API is very simple and can be explained with two examples:

  • GET https://municipios.rauln.com/distance/san-juan/mayaguez
{
  "result": {
    "distance": 8,
    "path": [
      "san-juan",
      "toa-baja",
      "dorado",
      "vega-alta",
      "manati",
      "ciales",
      "utuado",
      "lares",
      "las-marias",
      "mayaguez"
    ]
  }
}
  • GET https://municipios.rauln.com/adjacent/san-juan?distance=1
{
  "result": [
    "aguas-buenas",
    "caguas",
    "carolina",
    "catano",
    "guaynabo",
    "toa-baja",
    "trujillo-alto"
  ]
}

How

The data was obtained from from publicly available sources (see Credits). Graph creation and traversal is handled by NetworkX. The API was written using Flask, the code runs in AWS Lambda behind an AWS API Gateway and is managed via Zappa.

Why

I needed to know the answer to the following type of question: What are the three municipalities nearest to Guaynabo? I'm building an open source API which would find that sort of information useful. I'm sharing the information via code/API in case someone else finds it useful too!

Processes

  1. Manually edit the country adjacency text file to make it easier to parse

  2. Parse the text file with utils/parse_country_adjacency.py

  3. Store the resulting JSON in data/municipality_adjacency.json

  4. Process the JSON, generate a graph and write the graph to a file with utils/generate_adjacency_list.py

  5. Use the resulting data/adjacency_list.gz in the API to calculate adjacency and distance data for municipalities.

Credits

Municipality adjacency data obtained from publicly available Census data.