Search code examples
pythonapiflask-restful

Build a RESTful API server using FLASK?


I have a python function which takes a JSON object as an input and returns a 'YES/NO' output. Now, I am trying to convert it into an API server, so that another API can call it, pass the JSON and my API server can return a 'YES/NO'.

I read about Flask-RESTFul and looked at few examples. But all of them are written from the perspective of API client, like an API to read a todo list or read data from a db etc.

Could someone give an example of 2 small scripts - one acting as an API server and another acting as an API client. The API client calls the API server and passes on the following JSON -

{'fruit_1':'apple', 'fruit_2':'melon'}

and the API server returns 'apple' as an output.

Thanks in advance!


Solution

  • Here is a sample Restful api code.

    server side code

    from flask import Flask, request
    from flask_restful import Resource, Api
    
    app = Flask(__name__)
    api = Api(app)
    
    class MyResource(Resource):
        def post(self):
            data = request.data
            # Process data
            return {'message': 'YES/NO'}
    
    api.add_resource(MyResource, '/')
    
    if __name__ == '__main__':
        app.run(debug=True)
    

    client side code

    import json
    import requests
    url = 'http://127.0.0.1:5000'
    data = json.dumps({'fruit_1':'apple', 'fruit_2':'melon'})
    headers = {'Content-Type': 'application/json'}
    response = requests.post(url, data=data, headers=headers)
    print(response.json()['message'])