Hi guys, In this post, we will be building a rest API in python using a microframework called Flask. There are basically two methods to create a Rest API using a flask. If you looking to find out more about Flask do check out my post on Introduction To Flask.
Method I - Using Only Flask
The first method is to use only flask without any other packages
# importing... | |
from flask import Flask, render_template, Response ,request, url_for, redirect, send_from_directory, Markup, session, flash, jsonify | |
import json | |
# app confog(typo) | |
app = Flask(__name__) | |
# a simple route | |
@app.route("/") | |
def hello_wordl(): | |
data= { | |
'name': 'name' | |
} | |
return json.dumps(data) | |
# running the app | |
if __name__ == '__main__': | |
app.run() | |
Method II - Using Flask API
In this method, we use a package called flask API
# using flask_restful | |
from flask import Flask, jsonify, request | |
from flask_restful import Resource, Api | |
# creating the flask app | |
app = Flask(__name__) | |
# creating an API object | |
api = Api(app) | |
# making a class for a particular resource | |
# the get, post methods correspond to get and post requests | |
# they are automatically mapped by flask_restful. | |
# other methods include put, delete, etc. | |
class Hello_World(Resource): | |
# corresponds to the GET request. | |
# this function is called whenever there | |
# is a GET request for this resource | |
def get(self): | |
return jsonify({'message': 'hello world'}) | |
# Corresponds to POST request | |
def post(self): | |
data = request.get_json() # status code | |
return jsonify({'data': data}), 201 | |
# adding the defined resources along with their corresponding urls | |
api.add_resource(Hello_World, '/') | |
# driver function | |
if __name__ == '__main__': | |
app.run(debug = True) |
Conclusion
- These are a simple way to create API in Python. You could also use FastAPI(A New post on it coming soon!).
- Do Consider Digital Ocean if you are trying to host your application.
Top comments (0)