DEV Community

hardik singh
hardik singh

Posted on

learn to make a RESTful API with flask!

so what are we building here?

we will be building a very simple and basic API which can showcase some stats of various countries with a pre existing dataset in the form of a csv. to begin, download this dataset and save it in your working directory

getting the data from the csv

first we will get the data from the csv and format it all in the form of a dictionary, so that we can display this dictionary via our api

#this bit is to set up the csv file as pandas data frame object. it will now become easier to work with our data!
import pandas
dataset = pandas.read_csv('countries of the world.csv')
Enter fullscreen mode Exit fullscreen mode

now we will write a function which can give us the data of a specified country!

def InfoAboutCountry(country):
    headers = list(dataset.head(0))
    country_data = dataset.loc[dataset['Country'] == country+' '].values[0]
    return dict(zip(headers, country_data))
Enter fullscreen mode Exit fullscreen mode

so first we make a variable called 'headers' which will store all the parameters in the form of a list.
now we retrieve the data of the specified country using the loc function.
finally we zip them together and then explicitly convert it into a dictionary!
we will get the following output if we call this function for 'Australia'Image description

now on to making the api!

we first import our modules and then make a flask app and then initialize our api with the flask app which we just made

from flask import Flask
from flask_restful import Resource, Api, reqparse

app = Flask(__name__)
api = Api(app)
Enter fullscreen mode Exit fullscreen mode

now we make an api instance and add a Resource to it. Then we make a parser object which can help us to parse multiple arguments in the form of a single request. and finally we add an argument which needs to be parsed(in our case country)

class CountryAPI(Resource):
    def get(self):
        parser = reqparse.RequestParser()
        parser.add_argument('country', type=str)
Enter fullscreen mode Exit fullscreen mode

we then get the argument and call our function and return the data

class CountryAPI(Resource):
    def get(self):
        parser = reqparse.RequestParser()
        parser.add_argument('country', type=str)
        country = dict(parser.parse_args())['country']
        data = InfoAboutCountry(country)
        return data
Enter fullscreen mode Exit fullscreen mode

now to finsh things up we add this resource to our api and run the flask app

api.add_resource(CountryAPI, '/data', endpoint='data')
app.run()
Enter fullscreen mode Exit fullscreen mode

final output

Image description
as you can see our api returns the data we require!

code

you can find the code here!
https://gist.github.com/realhardik18/6d9975e8b21989afadd836c800df8b31

Top comments (0)