DEV Community

Cover image for Making a REST API Using Python - Flask
Raghav Mrituanjaya
Raghav Mrituanjaya

Posted on • Edited on • Originally published at thegogamicblog.xyz

3

Making a REST API Using Python - Flask

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)
view raw flask_method.py hosted with ❤ by GitHub

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.

API Trace View

How I Cut 22.3 Seconds Off an API Call with Sentry

Struggling with slow API calls? Dan Mindru walks through how he used Sentry's new Trace View feature to shave off 22.3 seconds from an API call.

Get a practical walkthrough of how to identify bottlenecks, split tasks into multiple parallel tasks, identify slow AI model calls, and more.

Read more →

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay