Rizzit Rizzit - 1 month ago 12
Python Question

How to pass data from client to REST API

I try to make an API for my Application. I want the client to pass a phone number as data to my API, so that my API can save the phone number to a MySQL DB.

What I have until now, my API:

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


app = Flask(__name__)


tasks = [
{
'id': 1,
'title': u'Create Incident',
'description': u'SYNC, QLTY, INFO',
'done': False
},
{
'id': 2,
'title': u'Close Incident',
'description': u'RFI, ERROR, RESOLVED',
'done': False
}
]


@app.route('/var/www/html/olotool/API/<int:task_id>', methods=['GET'])
def get_task(task_id):
task = [task for task in tasks if task['id'] == task_id]
if len(task) == 0:
abort(404)
return jsonify({'task': task[0]})



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


If i use curl:

curl http://127.0.0.1:5000/var/www/html/olotool/API/2
{
"task": {
"description": "RFI, ERROR, RESOLVED",
"done": false,
"id": 2,
"title": "Close Incident"
}


I receive an answer, now how can I pass a number trough this so that my API can connect to MySQL and save the number there?

Answer

Thank you SO community for not helping at all. I managed to help myself, I post this information for people with same problem:

https://github.com/RoyHolzem/API/blob/master/myAPI.py

Explanation:

The client gives you (POST Request) information, this information can then be saved in your dB by your API, as an example with cURL:

curl -i -H "Content-Type: application/json" -X POST -d '{"sid":"131001086184","text":"SAMPLE_TEXT","tlf":"phonenumber","ctc":"mobilenumber","fbm":"john@doe.com"}' http://localhost:5000/todo/api/v1.0/tasks

Your API catches these information in this part:

@app.route('/todo/api/v1.0/tasks', methods=['POST'])
def create_task():
    if not request.json or not 'sid' in request.json:
        abort(400)

    opr = request.json['opr']
    ctc = request.json['ctc']
    sid = request.json['sid']
    tlf = request.json['tlf']
text = request.json['text']

from here on you just tell python to save whatever you need into your dB.

Comments