Python web services using Flask

I’m a firm believer of basics, so before we deep dive into something really interesting and new, I feel its mandate to make you unravel with the basic terms and technologies which we will be using in this post.

In this tutorial you’ll be creating web services using Python – Flask.

Prerequisite:  The prerequisite of this tutorial is you must know the basics of Python, you can find my series of Python Here  some exposure to programming some client-server understanding basics of REST full web-services and JSON.

Tools, Terminologies, and Technologies :

  1. Python: Python is General Purpose High Level Programming Language. General Purpose means it can be used for multiple application such as Data Science, Machine Learning, Desktop Application, Web Application, Scripts etc. High Level Programming Language means human understandable language i.e. Human readable.
  2. Flask: Flask is a popular web framework written in Python, used for development of web application.
  3. REST: A RESTful API is an application program interface that  used uses HTTP requests to GET, PUT, POST and DELETE data.
  4. JSON: JSON, or JavaScript Object Notation, is a minimal, readable format for structuring data or exchanging the data.

We will start with creating a RESTful web services using Python and Flask.

Create a folder Student in your desktop and open terminal

$ cd Student
$ pip install Flask

Now we have Flask installed let’s create a simple web application. Inside the student create a file app.py. 

Open any Text Editor and write the following code I’ll be using Atom you can use notepad or notepad++ or any other editor, inside the file app.py.

 from flask import Flask
app = Flask(_name_)
@app.route('/')
def hello_world():
return 'Hello World'
if name == 'main':
app.run()

This is a simple Hello Nuclear Geeks program which will print Hello Nuclear Geeks to run open the terminal and type

$ cd Student
$ python app.py

Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)

You will get the following output. Copy and paste this to your browser and see Hello Nuclear Geeks flashing!!!

Now its time to create web services !!! This tutorial will not have database interaction with Python, I’ll be writing one soon. Here we will be using our own memory there we will be storing our JSON data.

Write the following code inside the app.py file.

 from flask import Flask, jsonify
app = Flask(name)
Student = [
{
'id': 1,
'firstName': 'Aditya',
'lastName': 'Malviya',
'age': '24'
},
{
'id': 2,
'firstName': 'Aman',
'lastName': 'Mehta',
'age': '25'
},
{
'id': 3,
'firstName': 'Nuclear',
'lastName': 'Geeks',
'age': '26'
}
]
@app.route('/Student/', methods=['GET'])
  def get_Student():
  return jsonify({'tasks': Student})
if name == 'main':
  app.run()

So we’ve create an array of dictionary in our memory, Here we have get_Student() function which will fetch all the Students from our memory. This is the example of GET Request. To run the above copy and paste this to your browser http://127.0.0.1:5000/Student/”  and hit Enter you’ll get the list of students or enter the following command in the terminal and hit Enter.

curl -i http://localhost:5000/Student/ 

HTTP/1.0 200 OK Content-Type: application/json Content-Length: 199 Server: Werkzeug/0.14.1 Python/2.7.15 Date: Fri, 31 Aug 2018 16:23:13 GMT {"tasks":[{"age":"24","firstName":"Aditya","lastName":"Malviya","id":1},{"age":"25","firstName":"Aman","lastName":"Mehta","id":2},{"age":"26","firstName":"Nuclear","lastName":"Geeks","id":3}]}

Next is out POST Request, Here we will be posting one more Student data into our existing data. The request.json will have the request data, but only if it came marked as JSON.  We will append the new task in our  Student array, and then respond to the client with the added task.

Write the following code inside the app.py file.

@app.route('/Student/', methods=['POST'])
def add_task():
student = {
'id': Student[-1]['id'] + 1,
'firstName': request.json['firstName'],
'lastName': request.json.get('lastName', ""),
'age': request.json.get('age',"27")
}
Student.append(student)
  return jsonify({'student': student}), 201

So here we’ve created a new function for adding the Student data in our array, we will be taking the same from the user and appending to our data. To run the following code copy paste into your terminal and hit Enter.

curl -i -H "Content-Type: application/json" -X POST -d '{"firstName":"SAM"}' http://127.0.0.1:5000/Student/

After running following command in the terminal you will see following output.

HTTP/1.0 201 CREATED

Content-Type: application/json

Content-Length: 66

Server: Werkzeug/0.14.1 Python/2.7.15

Date: Sat, 01 Sep 2018 05:19:12 GMT

{"student":{"age":"27","firstName":"SAM","lastName":"","id":4}}

And you’ve successfully posted your data!!! Simple isn’t it?…  You can fetch all the student data by our first command.

Copy and paste this to your browser http://127.0.0.1:5000/Student/”  and hit Enter you’ll get the list of students or enter the following command in the terminal and hit Enter.

curl -i http://localhost:5000/Student/

I hope this was an easy introduction to RESTful API using Flask….we will be interacting with mySQL using Python Flask in next tutorial.

2 thoughts on “Python web services using Flask

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s