How to Create API in Python
An API, Application Programming Interface, is a server that you can use to retrieve and send data to using code. APIs are most commonly used to retrieve data.
In this article, we will learn to create an REST API using Flask framework of Python. REST stands for REpresentational State Transfer and is an architectural style used in modern web development. It defines a set or rules/constraints for a web application to send and receive data.
Let’s see how to create an REST API using Flask framework:
We are using two functions: One function to just return or print the data sent through GET or POST and another function to calculate the square of a number sent through GET request and print it.
from flask import Flask, jsonify, request # creating a Flask app app = Flask(__name__) # on the terminal type: curl http://127.0.0.1:5000/ # returns hello world! when we use GET. # returns the data that we send when we use POST. @app.route('/', methods = ['GET', 'POST']) def home(): if(request.method == 'GET'): data = "hello world!" return jsonify({'Message': data}) # A simple function to calculate the square of a number # the number to be squared is sent in the URL when we use GET # on the terminal type: curl http://127.0.0.1:5000 / home / 10 # this returns 100 (square of 10) @app.route('/home/<int:num>', methods = ['GET']) def disp(num): return jsonify({'Value': num**2}) # driver function if __name__ == '__main__': app.run(debug = True)
Output: