Can I create a Django Rest Framework API with Geojson format without having a model

611 views Asked by At

I have a Django app that requests data from an external API and my goal is to convert that data which is returned as list/dictionary format into a new REST API with a Geojson format.

I came across django-rest-framework-gis but I don't know if I could use it without having a Model. But if so, how?

1

There are 1 answers

0
MarcelCode On

I think the best way is to use the python library geojson

pip install geojson

If you do not have a Model like in geodjango you have to explicitly describe the geometry from the data you have.

from geojson import Point, Feature, FeatureCollection

data = [
    {
        "id": 1,
        "address": "742 Evergreen Terrace",
        "city": "Springfield",
        "lon": -123.02,
        "lat": 44.04
    },
    {
        "id": 2,
        "address": "111 Spring Terrace",
        "city": "New Mexico",
        "lon": -124.02,
        "lat": 45.04
    }
]


def to_geojson(entries):
    features = []

    for entry in entries:
        point = Point((entry["lon"], entry["lat"]))

        del entry["lon"]
        del entry["lat"]

        feature = Feature(geometry=point, properties=entry)
        features.append(feature)

    return FeatureCollection(features)


if __name__ == '__main__':
    my_geojson = to_geojson(data)

    print(my_geojson)
  • Create the point geometry from lon, lat (Could also be another geometry type)
  • Create a feature with the created geometry and add the dictionary as properties. Note that I deleted lon, lat entries from the dictionary to not show up as properties.
  • Create A feature collection from multiple features

Result:

{"features": [{"geometry": {"coordinates": [-123.02, 44.04], "type": "Point"}, "properties": {"address": "742 Evergreen Terrace", "city": "Springfield", "id": 1}, "type": "Feature"}, {"geometry": {"coordinates": [-124.02, 45.04], "type": "Point"}, "properties": {"address": "111 Spring Terrace", "city": "New Mexico", "id": 2}, "type": "Feature"}], "type": "FeatureCollection"}

More Info here: Documentation Geojson Library