Create a geospatial API using Python and Flask

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hello everyone it has been a very long time since I created a video on my channel I guess I have been busy with different life issues anyways the purpose of this video is to share with you an example on how to implement a simple API and a simple server using Python and flask for running geospatial functionality we will basically pass a wgs84 coordinates and a buffer distance in kilometer to the server using the API and we'll get back from the server a buffered polygon along with the point we passed as geo JSON outlet so first thing if you are not familiar with the term API the term stands for application programming interface an API can be defined as the mechanism of asking a server for specific data the server can either retrieve the data from a database or it can make its own computations without the need of accessing a database so we request from a server and the server respond to our request with the results request and respond are the verbs used to describe the workflow of an API the response is returned to the client which can be a mobile app a web browser or maybe a digital billboard digital billboards are the digital signs you can find on the street or inside shopping malls displaying for instance updated weather information there are two main types of API s-- rest and soap explaining the difference is out of the scope of what we are doing here but I have to mention that we are building a REST API an API is usually used by developers including front-end developers and mobile native app developers it is usually structured as a URL with parameters the URL with parameters can be referred to as an API endpoint this is a fake example of a fake URL or a fake API as you can see it's requesting two parameters in real life searching for example an address on Google Maps is an API call searching for a product on Amazon is an API call and searching for content on Twitter or other social media is an API call as well so how developers built API sand servers to respond to requests from clients actually there are different options of programming languages and frameworks the two common examples are no js' with Express and Python with flask Java PHP dotnet can also be used with other frameworks to do so in this video we will use Python and flask here Python is the programming language and flask is the framework the flask framework makes it much easier to create a server and an API or more than one API in Python by writing less code compared to doing everything in Python natively I'm not going to explain details on how to use flask in this video we will focus more on the whole concept of how to integrate geospatial functionality in an API endpoint implementation it is worth mentioning that flask can respond or render data from a server as HTML or JSON or other formats such as eczema okay now I have placed all the code you need to follow along on my github account you can find the link on the video's description first think it is better to create a separate environment on our machine your computer might have other installed packages for other applications and buy packages I mean Python packages having a separate environment is used to avoid conflicts between packages for different applications this is in general is a good practice because you might have two applications on your machine using two different versions of one specific package for instance I have Python 3 installed on my Mac and right now I'm under the Documents folder ok so as you can see I have the Geo app so this is the code that was downloaded from github to create the environment you can type and you can call it whatever you want so I'm gonna call it GU handy ok the dot forward slash here means that creating the environment in the same path which is documents so now let me tap LS and as you can see it created the environment folder here so in Python the event package is used to install separate environments for your applications by the way this command runs on Mac on Linux environments such as Ubuntu I believe it is the same on Windows but if it doesn't work and you're using Windows you can double check on Google now if you want to activate the environment you can type source if you are a Windows user you can type this command so you can see right now we're in the environment so whatever packages we installed on this environment should be different from the regular prompt or from other environments on the same machine just to let you know you can type the activate at any time to go back to your regular prompt and exit the development environment here I'll go back to the environment ok now before I install the packages that we need for this application let me show you the path on where these packages should be installed so this is the path so as you can see pip is already there but our packages are not there yet ok now we can use pip to install all the required packages that we need so to do that we can type it install our you app so right now we're go into the working folder and there is the requirements that txt okay so this file requirements txt basically has all the packages that we need to install to build our app so this command basically will install all the packages listed under the requirements that the XD I'll click enter ok so now it's installing everything that we have okay now let's double check everything is installed under the same path that I mentioned site packages ok so we can see flask is installed EGU JSON is installed Shapley is installed these are the only three packages that I need to build this app ok let me clear everything here okay right now we're inside the environment let's navigate to the working folder so it's GU app that is confirm here ok so we are under the geo app now let me type LS so as you can see there's a subfolder called app and there is the requirements txt file that we used before to install the packages we need for this app I have Visual Studio code installed on my machine so if I type code dot here what happens it will open visual studio code on this specific path ok so this is the requirements txt file and as you can see there is Shapley geo JSON and flask so I'm using flask to build a server and to respond to API calls I'm using Shapley to invoke the geospatial functionality and I'm using geo JSON to create a Geo JSON response and flask will send it back to the client ok under the apps folder you can see main that py this is like the entry file of our server ok so let me close this it's better now so as you can see the first three lines are basically imports so from flask we're importing the flask class we're importing three different functions render template JSON file and request and Shapley package has a geometry module and under the geometry module there is the point class and there is a mapping function and from geo JSON I'm importing point class polygons class feature class and feature collection class if you notice something here both shapely and geo JSON have point classes so to avoid errors in the code I created aliases for both so for the point class from shapely I gave it an alias of shapely point and from the Geo JSON I call it goj point and I give another alias for goj polygon next this is actually how simply it is to create a server using flask I will talk later about this line of code now let's continue flask uses decorators in Python for emphasizing the routes routes are basically what is written after the site name forward slash in this example if you type localhost port forward slash or localhost port forward slash index or localhost port forward slash home it will render the output from this function the rendering here is not related to the video but I just want to show you how to render HTML easily with flask so this function render template the one we imported here basically what it does it will look for a subfolder under the app folder called templates and inside it it will search for the file given which is indexed at HTML so if I click here this is a very basic HTML file now let's go back to the code so now this is the geospatial function or the geospatial API it's called buffer point now when you look into the route this means that if you type localhost port forward slash buffer point plus the query string this function will be activated so the query string will contain three parameters longitude latitude and buffer distance we use the request function from flask to get the values of these parameters we can see this on these lines getting the values of the three parameters longitude latitude and buffer distance now we need to check if the given values for longitude latitude and buffer distance are valid error response is a dictionary here so we will use it to generate the error and then to convert it to a JSON format for the response the error will be rendered on the browser so the developer can see it and understand the problem on how he or she made the error on one of the parameters so let me explain it for longitude and before I do that I want to mention that I should have used a try except block instead of the F else block sorry for that and this is also the same issue for validating latitude and validating the buffer distance the code on github is updated with try accept blocks for the three parameters okay flask gets parameters in string format so in the try block I'm checking if the given longitude drink is numeric otherwise what we're doing here is adding two keys for the error response dictionary and explaining the problem and then we're returning the dictionary but we pass it to a function called JSON Fi and this function was imported also above in the code and basically what it does it converts the dictionary into a JSON format okay now it's a good time actually to go back and explain what does this line mean so here flask by default sort the keys given in JSON or in a dictionary that is converted to JSON for the response so we don't want to do that so if I go back here so you see here longitude error value given so this is the correct order but let's say for example that we want this key to appear first in the response before the longitude so in other words we are disabling flask's default alphabetical ordering okay now let's move to the next check so basically what I'm doing here is checking if the longitude value is less than negative 180 or bigger than 180 which means it's out of range in this case I will return this error and this is the same actually for latitude as you can see for latitude the ranges from negative 90 to 90 and for the buffer distance so I'm limiting between 0.001 kilometer which means it's 1 meter up to 100 kilometers if it's more than that then I'm just limiting this API not to do anything ok now let's continue all right ok so in this line of code what I'm doing is I'm creating a shapely point by passing the longitude and the latitude I've also added some documentation to help you understand what's going on so on line 80 what I'm doing here is I'm creating a buffer so this is a polygon and basically under Shapley the point object there is a method called buffer and I'm passing the buffer distance divided by 111 so why am i doing this the reason is that Shapley is expecting the buffer distance in degrees not in kilometers so this is roughly how many kilometers in one degree and this is specifically the conversion closer to the equator it is different if you move away from the equator but for the sake of simplification we're just using this number now on line 83 what I'm doing here is using the mapping function to create a dictionary from the polygon object and the reason I'm doing so is that the mapping function will create a dictionary and one of the keys will be called coordinates and I need these coordinates so I can create the Geo JSON object using the Geo JSON package so here I'm just getting the coordinates and passing into this variable so by the end of this line we're done using Shapley and now we're using the geo json library so for the geo json library here what i'm doing is basically creating two features so one feature will be the point given and another feature which is the polygon created by Shapley so as you can see in part one what I'm doing it's basically creating a GU JSON feature using GU JSON point by passing longitude and latitude then I'm adding some properties so if you are not familiar with the Geo JSON format properties have both attributes and symbology options for features so here I'm giving it an attribute of name and I just called it the API point and for the attribute I assigned the color red this is the second feature which is the buffer that was created using Shapley and basically I'm passing its coordinates here so the polygons class under the Geo JSON package requires only coordinates and once I create the polygon I pass it to the feature class so I have two features right now I have one feature for a point another feature for the polygon and I'm passing some properties here so this is an attribute name and here these are for symbology so the stroke is the color of the boundary of the polygon and I assign it to blue the fill of the polygon is also blue but the fill has an opacity of 30% if you have any questions about properties or what is happening with the Geo JSON you can post your questions in the comment section now on line 100 what I'm doing here I'm using the feature collection class and basically what it needs it's a list and as you can see I'm passing a list here of all the features that you need to add to the future collection then at the end I'm returning the feature collection as JSON format so here what's happening it's returning the feature collection in a Geo JSON format and at the end here we're just running the application and if you see here I'm passing a parameter called debug equal true and basically what it does it will allow you to see the changes on the server instantly without the need to restart the server okay now let's run the application if I go here before I do that I need to double check that I'm using the environment so the one that was selected was the regular environment user bin Python so I need to change it to this this one here geo a pin so if I click here then right click and I select run Python file in terminal okay so like right there so this is the URL let me just copy it if I copy the URL for the localhost okay now I'm in Chrome if I paste it here enter ok so now it's reading from the server and I forgot to mention this is the port number so this is the default port for flask you can change it if you want to so now let's try the API ok remember like when we pass parameters we have to use the question mark here first so if I say for example longitude equal 1 on 1 point 7 and right 2 3 4 2 3 point 1 1 & 4 distance is equal to say 25 kilometers let me get interested ok let me just go back and make sure that didn't make a mistake here so function name so C or the route maybe yeah oh sorry that's okay now we got it so this is the output so we have the feature collection and this is the first feature which is the point and as you can see this is what I called it in the code API point and this is the next one which is the polygon and you should see the properties it's called the API point buffer okay now by right-click it save as and you need to double check with the format so instead of JSON select all files okay so I'm just gonna save it under documents here click Save so now let's test our result so if you type geo json dot i/o so if i go to open file it should make me somewhere next to kuala lumpur anyway so this is the output and as you notice in geo json you can have points polygons and even lines in one file which is different from shape files for example just to let you know now let's go back latitude so set of three let's make it 103 okay so you can see here what it's saying it says the latitude or it's out of range from negative 90 to 90 sorry for this I mean I don't know to move it but you get the idea and the value given in the API is this value one last note is that you have to take care of errors while building api's thank you for listening and I hope you learn something here
Info
Channel: Tips for GIS
Views: 3,924
Rating: undefined out of 5
Keywords: Python, Flask, API, GIS, Geospatial, Shapely, GeoJSON, GIS programming, Geospatial programming, Spatial, Spatial programming, Open source, Open source GIS
Id: jPd6nCfC3pY
Channel Id: undefined
Length: 21min 50sec (1310 seconds)
Published: Fri Jun 19 2020
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.