Skip to content
Sign upLog in
← Back to Community
How to make Rest Api in Python
Profile icon
has Hacker Plan


In today's lesson, we will learn how to build basic Rest Api in Python and Flask. We will specifically focus on two different way of creating apis, both will be using flask.
List of two ways.

  1. using flask
  2. using flask extension called flask restful

In this Lesson we are going to use flask restful to make our final api.
But I'm also going to show to how to create one in `flask

Note! using flask is not the most official way of creating api. Flask is not efficient, code will look bad and have difficulty managing large files.
flask restful flask extension restful is the best way of creating api. Because it handlea big files wasily. Very easy to work with And it was created special for making rest apis.
I recommend you should use flask restful

Here what our final api will look like
Api final Result
It will generate random content from a category and print it out in json format

What is REST?

Representational State Transfer (REST) is a software architectural style that defines a set of constraints to be used for creating web services. Web services that conform to the REST architectural style, termed RESTful web services, provide interoperability between computer systems on the Internet. RESTful web services allow the requesting systems to access and manipulate textual representations of web resources by using a uniform and predefined set of stateless operations. Other kinds of web services, such as SOAP web services, expose their own arbitrary sets of operations. In a RESTful web service, requests made to a resource's URI will elicit a response with a payload formatted in either HTML, XML, JSON, or some other format.
For more info click here

We will only work with json format


  • Basic Python knowledge
  • Flask
  • Flask-Restful
  • Jsonify
  • json


Inside your repl, creating an empty file called requirements.txt. Once you have to empty txt file ready, copy and paste this Flask==1.0.2 to your requirements.txt to install flask.

Installation Successful
If this started to happen, that mean flask have been install, and if not, something is wrong and should re-copy and paste Flask==1.0.2
To install flask-restful, repeat the same procedure but use this line Flask-RESTful==0.3.6

Creating web server

We'll need to create basic web server. We need web server to run our code on
here the basic code for creating basic web server

from flask import Flask from threading import Thread app = Flask('') @app.route('/') def home(): return "I'm alive" def run():'',port=8080) t = Thread(target=run) t.start()

I'm not going to explain this code, as I'm bad when it come to server stuff. But up there we just created a simple server.

if you run this code this screen is going to pop up on top right hand right with this text i'm alive. Now we have successfully created a web server.


REST have 4 methods:

  • GET
  • PUT
  • POST

In this tutorial, we ony going to work with GET method.

Creating api

first we need to import another flask extension jsonify.

from flask import jsonify

we need jsonify to convert data in json and send it out to our server.
Important Note:- we're going only going to work with json data, because json can be used in almost every modern language.

from flask import Flask, jsonify from threading import Thread app = Flask('') #make sure you code is between this code t = Thread(target=run) t.start()

here's a example of GET methods

from flask import Flask, jsonify from threading import Thread app = Flask('') @app.route('/') def home(): return "I'm alive" @app.route('/api/add', methods=['GET']) def add(): return jsonify({"2 + 2": 2 + 2}) def run():'',port=7000) t = Thread(target=run) t.start()
@app.route('/api/add', methods=['GET'])

/api/add is our api endpoint. you can name it what ever you want, im just gonna called it that. we need an endpoint to get to make requests to content, without any endpoint it will give you an error or simply return you home page if available.
You also noticed that we in our

. we have methods. We use methods to tell what kind of rest option, we are using. In this case we are GET.

ENDPOINT= your web server url + your app route
so my url is + route /api/add
our endpoint is

Note:- your url name will be different than mine. so put your url name and route together.

If you run my example you will get this result.
{"2 + 2":4}

I recommend running my example first and once you have hold of it, then run you're owns.

Now in this example we will take user input and convert this to json data. I'm going to use to previous example but add user input. So user will put any number and it will double user input.

@app.route('/api/add/<int:num>', methods=['GET']) def add(num): return jsonify({f"{num} + {num}" : num + num})

You may have noticed that our in route we have this <int:num>. This is how to take input.
int is specify what type of content is it. And num is the name of variable we will storing our input. Once we have our input.
Then we are going to use jsonify to convert data into json format and print it out on server.
If you run this code now and endpoint /api/add/<any num you want> i'll be using 23, json data should look something like that.

{"23 + 23" = 46}

Now he's another example that takes string as input

@app.route('/api/name/<string:name>', methods=['GET']) def get_name(name): return jsonify({"Your name": name})

we bascially did same thing, just change our variable type to string. and if we run this example result show look like this

{"Your name": "bad"}

That all i have for flask. If you wanna continued with flask, Good Luck, but i'll suggest you checkout flask-restful

Getting ready for flask-restful Api

So, the api i'm creating have two main categories, facts and quote. And then inside the folder, there are four json files, that contain some sort of json content. I hope this made any sense to you. If not, then i'm sorry


first we need to import two extension from flask-restful, We need Resource, and Api.

from flask_restful import Resource, Api

Here a simple example of flask-restful

from flask import Flask, jsonify from threading import Thread from flask_restful import Resource, Api app = Flask('') api = Api(app) class Test(Resource): def get(self): return "Example with Flask-Restful" #creating api endpoint api.add_resource(Test, '/api/restful') def run():'',port=7210) t = Thread(target=run) t.start()

If you compare this with flask. You can clearly see this is more readable, official and best.

How flask-restful works

first we need to build api on top of app.

app = Flask('') api = Api(app)

We just creating api. Now we dont need app. And we are going to use api to add new content.

class Test(Resource): def get(self): return "Example with Flask-Restful"

In flask-restful, all content need to be in class with Resource as parameters
Methods are a little different. You don't assign Methods in route endpoint, instead you add methods directly to class. def get(self): or def post(self)
Self: becuase we are using def inside class, so we need to add self as first parameter.

To create endpoint in flask-restful, it's pretty easy.
api.add_resource(<your class name>, <your endpoint>)
For this example
api.add_resource(Test, '/api/restful')

If you run this now. You should get this
"Example with Flask-Restful"

def get(self): return "Example with Flask-Restful"

As you see, we didn't use jsonify. WHY. Becuase the content we're returning in not json. So to return json data. Here's an example

def get(self): return jsonify({"Type": "flask-restful"})

Output should be

Creating final Api

Becuase i'm gonna be selecting random from json fromat, so i need to import random and also need to import json

import random import json

Now we are going to create a class called Facts. This class will return a random facts.

def get_facts(fact_type): if fact_type == "random": file_address = 'Facts/random.json' elif fact_type == "technology": file_address = 'Facts/technology.json' else: file_address = 'errormsg.json' with open(file_address, 'r') as factfile: data = json.load(factfile) fact = random.choice(list(data['Facts'])) return fact class Facts(Resource): def get(self, fact_type): return get_facts(fact_type) api.add_resource(Facts, '/api/facts/<string:fact_type>')

So what i did that, instead of adding everything to my Facts class, i created a new def, outside of class. Now everythime, I'm calling Facts endpoint. It's sending requests back to get_facts() and return the data to def get(). And then this whole return the data to our server.

Creating new separate data will make your code more readable.

you may wonder what this for

def get_facts(fact_type): if fact_type == "random": file_address = 'Facts/random.json' elif fact_type == "technology": file_address = 'Facts/technology.json' else: file_address = 'errormsg.json' with open(file_address, 'r') as factfile: data = json.load(factfile) fact = random.choice(list(data['Facts'])) return fact

fact_type is user input.

So i only want user to choose from my inputs, so im using if statement to check user input. If user input is equal to one of my inputs, I'm creating a new variable called file_address. This will contain file address i want to open.

with open(file_address, 'r') as factfile: data = json.load(factfile) fact = random.choice(list(data['Facts']))

now once if else are done. We need to open the file and select random items from it. Remember, we are storing file address in file_address. We are going to called this file factfile

Once we open the file, we need to load all content to json file.
data = json.load(factfile)
and now open we have all content in json file, we need to random select one.
fact = random.choice(list(data['Facts']))

data:- name of variable which contain our json content
data['Facts]: Facts is what we want from our json file. It will randomly select one thing from Facts and return to def get_fact and this will return everything to class Facts and this will return it to our server.

Now if you run your code, the output should look like this
Facts Results

Now we are going to do the same thing with Quotes. We'll create a class and remember to give Resource parameter to class.

def get_quotes(quote_type): if quote_type == "motivation": file_address = 'Quotes/motivation.json' elif quote_type == "funny": file_address = 'Quotes/funny.json' else: file_address = 'errormsg.json' with open(file_address, 'r') as quotefile: data = json.load(quotefile) quote = random.choice(list(data['Quotes'])) return quote class Quotes(Resource): def get(self, quote_type): return get_quotes(quote_type) api.add_resource(Quotes, '/api/quotes/<string:quote_type>')

So we are just doing the same thing we did previously.

Congrats, you have successfully created your first rest api.

I hope you learned something today
I know it's bad but i try my best to make a great tutorial

If you have any question dm me on discord, ask in official discord server or comment below

If you see any error or mistake. Please notify me.

Important Note:- your repl web server won't stay up 24/7. I will die after 60 min. So i suggest using free service UptimeRobot. If you never used UptimeRobot,
then read this tutorial for help

This api was just for tutorial. I'm not working on it anymore.
Please check out of my main api.

Source code

Profile icon
Profile icon
Profile icon
Profile icon
Profile icon
Profile icon
Profile icon
Profile icon
Profile icon
Profile icon
Profile icon

I like how in-depth this is. It is definitely helpful to anyone trying to create an API but not knowing how. Nice job!

Profile icon

This is a great help, Thanks!

Profile icon

hi, i made a flask based api with another person. It has loadtimes of 2 secs when 1 person calls and 6 secs when 2 people. Converting to flask_ restful will help?

Profile icon

the reason it takes long is that it webscrapes to get data

Profile icon

It dosent work, Line 3: ModuleNotFoundError: No module named 'flask_restful

Profile icon

Gives me an error
`Line 3: ModuleNotFoundError: No module named 'flask_restful'

Profile icon

Good work.

Profile icon

Found a minor typo. Took me a minute to figure out wasily was supposed to be easily. :)
I lead a dev support/API support desk and have for many years. I know the ins and outs of implementing a RESTful API, but have only rarely taken a look from the other side. Thanks, I'm looking forward to using this to update some of my testing tools.

Profile icon

Please tell me where was this spelling mistake.

Profile icon

nvm fixed

Profile icon

Btw you made a typo - fact_tpye -> fact_type. But love it!

Profile icon

@timmy_i_chen oof where? which line or section.

Profile icon

@timmy_i_chen nvm

Profile icon

there is a mistake in the first code example of the flask-restful:

class Test(Resource): def get(self): return "Example with Flask-Restful" #creating api endpoint api.add_resource(Facts, '/api/restful')

should be

api.add_resource(Test, '/api/restful')
Profile icon

hey, im having trouble finding this mistake. Can you please tell exactly where this mistake is? thanks

Profile icon

right after "Here a simple example of flask-restful"

Profile icon

fixed. Thanks

Profile icon

This is a great, well made tutorial. It deserves more attention for all the time an effort you've put into it. Cheers :)

Profile icon

thanks for support