DEV Community

Cover image for UNDERSTANDING AND IMPLEMENTING A SIMPLE PYTHON REST API
Ore-aruwaji tola
Ore-aruwaji tola

Posted on • Updated on

UNDERSTANDING AND IMPLEMENTING A SIMPLE PYTHON REST API

What is a RESTFUL API?

It is definitely an architectural style of building APis,
REST is the underlying architectural principle of the web. The amazing thing about the web is the fact that clients (browsers) and servers can interact in complex ways without the client knowing anything beforehand about the server and the resources it hosts. The key constraint is that the server and client must both agree on the media used, which in the case of the web is HTML.

A RESTful API -- also referred to as a RESTful web service -- is based on representational state transfer REST

A practical example of an api is when you enter the restaurant with someone, you want to order a food item for yourself and the person, there is a waiter to take in your request and prepares a response for you in the kitchen and gives it back to you, the waiter acts as the api

The waiter acts as HTTP and the kitchen is the web so it sends a request and the kitchen sends it back, the kitchen gives you the response back using HTTP response.

screenshot

Your standard database CRUD (Create, Read, Update, Delete) is translated to the HTTP verbs: POST, GET, PUT, DELETE. Following that convention and passing on the right parameters basically means that you have translated some of the business logic onto HTTP. It's as simple as that.

-- A GET should be used for requesting information from the web service.

-- A POST should be used to put data to a web server, where there is no specification as to where the web service should put the data. This may be considered the equivalent of an insert.

-- A PUT should be used when you want to specify where the data goes. This is an idempotent action as repeating it will not change anything on each repeated call. Alternatively this may be considered as the equivalent of an update.

-- And a DELETE is obviously to be used to delete some data or a resource from the web server.

Now,let us build a restful api that supports +,-,/,*
Method:POST
Resources:+,-,/,*

RESOURCE METHOD CHART

Resource method path used for/address parameters on errorcode/status
+ POST /add Adding two numbers X:int , y:int 200:ok, 300:missing
- POST /subtract Subtracting two numbers x:int, y:int 200:ok, 300:missing
* POST /multiply multiplying two numbers X:int, y:int 200:ok, 300:missing
/ POST /divide Dividing two numbers x:int, y:int 200:ok, 301:missing, 302:y is zero so it wont divide

CODEBASE

from flask import Flask, jsonify, request
from flask_restful import Api, Resource

app = Flask(__name__)
api = Api(app)


def checkPostedData(postedData, functionName):
    if (functionName == "add" or functionName == "subtract" or functionName == "multiply"):
        if "x" not in postedData or "y" not in postedData:
            return 301 #Missing parameter
        else:
            return 200
    elif (functionName == "division"):
        if "x" not in postedData or "y" not in postedData:
            return 301
        elif int(postedData["y"])==0:
            return 302
        else:
            return 200

class Add(Resource):
    def post(self):
        #If I am here, then the resouce Add was requested using the method POST

        #Step 1: Get posted data:
        postedData = request.get_json()

        #Steb 1b: Verify validity of posted data
        status_code = checkPostedData(postedData, "add")
        if (status_code!=200):
            retJson = {
                "Message": "An error happened",
                "Status Code":status_code
            }
            return jsonify(retJson)

        #If i am here, then status_code == 200
        x = postedData["x"]
        y = postedData["y"]
        x = int(x)
        y = int(y)

        #Step 2: Add the posted data
        ret = x+y
        retMap = {
            'Message': ret,
            'Status Code': 200
        }
        return jsonify(retMap)

class Subtract(Resource):
    def post(self):
        #If I am here, then the resouce Subtract was requested using the method POST

        #Step 1: Get posted data:
        postedData = request.get_json()

        #Steb 1b: Verify validity of posted data
        status_code = checkPostedData(postedData, "subtract")


        if (status_code!=200):
            retJson = {
                "Message": "An error happened",
                "Status Code":status_code
            }
            return jsonify(retJson)

        #If i am here, then status_code == 200
        x = postedData["x"]
        y = postedData["y"]
        x = int(x)
        y = int(y)

        #Step 2: Subtract the posted data
        ret = x-y
        retMap = {
            'Message': ret,
            'Status Code': 200
        }
        return jsonify(retMap)


class Multiply(Resource):
    def post(self):
        #If I am here, then the resouce Multiply was requested using the method POST

        #Step 1: Get posted data:
        postedData = request.get_json()

        #Steb 1b: Verify validity of posted data
        status_code = checkPostedData(postedData, "multiply")


        if (status_code!=200):
            retJson = {
                "Message": "An error happened",
                "Status Code":status_code
            }
            return jsonify(retJson)

        #If i am here, then status_code == 200
        x = postedData["x"]
        y = postedData["y"]
        x = int(x)
        y = int(y)

        #Step 2: Multiply the posted data
        ret = x*y
        retMap = {
            'Message': ret,
            'Status Code': 200
        }
        return jsonify(retMap)

class Divide(Resource):
    def post(self):
        #If I am here, then the resouce Divide was requested using the method POST

        #Step 1: Get posted data:
        postedData = request.get_json()

        #Steb 1b: Verify validity of posted data
        status_code = checkPostedData(postedData, "division")


        if (status_code!=200):
            retJson = {
                "Message": "An error happened",
                "Status Code":status_code
            }
            return jsonify(retJson)

        #If i am here, then status_code == 200
        x = postedData["x"]
        y = postedData["y"]
        x = int(x)
        y = int(y)

        #Step 2: Multiply the posted data
        ret = (x*1.0)/y
        retMap = {
            'Message': ret,
            'Status Code': 200
        }
        return jsonify(retMap)



api.add_resource(Add, "/add")
api.add_resource(Subtract, "/subtract")
api.add_resource(Multiply, "/multiply")
api.add_resource(Divide, "/division")

@app.route('/')
def hello_world():
    return "Hello World!"


if __name__=="__main__":
    app.run(debug=True)

Why not share the link for this post on Twitter ? Spread the word!

Don't forget to follow me on twitter

Thanks!

Top comments (0)