HomeBack-End & DatabasePython API Development Part2

Python API Development Part2

This is in continuation of my previous article for Todo App API. In this post we will some more advanced features to our todo app and improve our python skills

Generate ID For Todo

In our previous api, when we create a new todo we take the “id” from request json. Currently lets try two things

  1. Add Validation for ID that it should be unique
  2. Instead of taking ID from request json, generate a unique id always

Its expected you first try solution for this yourself i.e google and see if you can solve this yourself

 
global tasks
task = [task for task in tasks if task["id"] == id]
print(task) #this is use to debug and it will print value on your terminal
if len(task) > 0:
return jsonify(message="Duplicate ID")

Second,

 
global tasks
tasks.append({
"id": len(tasks) + 1,
"title": title,
"description": desc,
"done": False
})

You could also generate a UUID for a id? try it out

Update Task status to done

In this we will create another route to mark/unmark a task as done

 

def mark(task, status, task_id):
if task_id == task["id"]:
task["done"] = status

return task


@app.route("/todo/mark/<int:task_id>/<int:status>", methods=["PUT"])
def mark_task(task_id, status):

global tasks
if status == 1:
status = True
else:
status = False

tasks = [mark(task, status, task_id) for task in tasks]

return jsonify(tasks)

Add Due Date to tasks

For date operation, python has a library called datetime. In our request json, we will pass a date parameter “12/23/2018” and store that in our array.

 
@app.route('/todo', methods=["POST"])
def add_todo():
if not request.json:
abort(500)

title = request.json.get("title", None)
desc = request.json.get("description", "")

due = request.json.get("due" , None)

if due is not None:
due = datetime.datetime.strptime(due, "%d-%m-%Y")
else:
due = datetime.datetime.now()


global tasks
tasks.append({
"id": len(tasks) + 1,
"title": title,
"description": desc,
"done": False,
"due" : due
})
return jsonify(len(tasks))

SORT TASKS AS PER DUE DATE

Let’s add sort option to our GET route

 
def sort_due_date(x):
return x["due"]


@app.route('/todo', methods=["GET"])
@app.route('/todo/<string:direction>', methods=["GET"])
def todo(direction=None):
# direction is optional

if direction == "ASC":
direction = True
else:
direction = False

global tasks
if direction is not None:
tasks.sort(reverse=direction, key=sort_due_date)

return jsonify(tasks)

At this point we have covered different use cases and should have good understanding of flask/python basics now

Leave a Reply

Your email address will not be published. Required fields are marked *

%d bloggers like this: