Introduction
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 useflask restful
Here what our final api will look like
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
Requirements
- Basic Python knowledge
- Flask
- Flask-Restful
- Jsonify
- json
Installation
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.
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 repl.it
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():
app.run(host='0.0.0.0',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
REST have 4 methods:
- GET
- PUT
- POST
- DELETE
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
```python
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():
app.run(host='0.0.0.0',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 @app.route. 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 https://rest-api-python.badvillain01.repl.co
+ route /api/add
our endpoint ishttps://rest-api-python.badvillain01.repl.co/api/add
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
flask-restful
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():
app.run(host='0.0.0.0',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 withResource
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):
ordef post(self)
Self: becuase we are usingdef
inside class, so we need to addself
as first parameter.
To create endpoint
in flask-restful, it's pretty easy.api.add_resource(<your class name>, <your endpoint>)
For this exampleapi.add_resource(Test, '/api/restful')
If you run this now. You should get this"Example with Flask-Restful"
NOTE
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{"Type":"flask-restful"}
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 fromFacts
and return todef get_fact
and this will return everything toclass Facts
and this will return it to our server.
Now if you run your code, the output should look like this
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 repl.it 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 usedUptimeRobot
,
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
Good work.
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.
@ThomasHagan Please tell me where was this spelling mistake.
@ThomasHagan nvm fixed
Btw you made a typo - fact_tpye
-> fact_type
. But love it!
@timmy_i_chen oof where? which line or section.
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')
@romanesko hey, im having trouble finding this mistake. Can you please tell exactly where this mistake is? thanks
@badvillain01 right after "Here a simple example of flask-restful"
@romanesko fixed. Thanks
This is a great, well made tutorial. It deserves more attention for all the time an effort you've put into it. Cheers :)
@DrankArizonaIce thanks for support
I like how in-depth this is. It is definitely helpful to anyone trying to create an API but not knowing how. Nice job!