VOOZH about

URL: https://dzone.com/articles/how-to-build-an-api-with-python-flask

⇱ How To Build an API With Python Flask


Related

  1. DZone
  2. Coding
  3. Languages
  4. How To Build an API With Python Flask

How To Build an API With Python Flask

Python Flask is a popular framework for building web applications and APIs in Python. This example will review how to create a simple rest API Flask tutorial.

By Dec. 09, 23 · Tutorial
Likes
Comment
Save
4.7K Views

Join the DZone community and get the full member experience.

Join For Free

Python Flask is a popular framework for building web applications and APIs in Python. It provides developers with a quick and easy way to create RESTful APIs that can be used by other software applications. Flask is lightweight and requires minimal setup, making it a great choice for building small to medium-sized APIs. This makes Flask an ideal choice for developers looking to build robust and scalable APIs in Python. This example will review how to create a simple rest API Flask tutorial.

Pre-Requisites

Before we start, we must ensure that a couple of prerequisites are completed. To follow along and run this tutorial, you will need to:

  1. Install Python
  2. Have an IDE to edit your code
  3. Install Postman so that you can test the endpoint

After all 3 of these prerequisites are completed, we can begin!

Creating the Base Project

To create the base project, the first thing we will do is create a folder named python-flask-api in your chosen directory.

With the new folder created, we will open a terminal in the root of the folder so that commands can be executed to build and run our Python project. Once your terminal is pointed to the root directory of your project, run the following commands so you can initialize the Python Rest API Flask project and manage the dependencies.

First, we will use pip to install Flask in the project directory. To do this, run the command below.

Shell
pip install Flask


Writing the Code

In our first line of code in the app.py file, we will import the modules for json, Flask, jsonify, and request.

Python
import json
from flask import Flask, jsonify, request


Next, we will create a new Flask application by adding the following code just below our import statements.

Python
app = Flask(__name__)


Next, to give our API a little bit of data to work with, we will define an array of employee objects with an ID and name.

Python
employees = [ { 'id': 1, 'name': 'Ashley' }, { 'id': 2, 'name': 'Kate' }, { 'id': 3, 'name': 'Joe' }]


To define our API endpoint, we will now add code to define a route for GET requests to the ‘/employees’ endpoint. This will return all employees (from our employees array defined above) in JSON format.

Python
@app.route('/employees', methods=['GET'])
def get_employees():
 return jsonify(employees)


On top of our GET method, we will also define a route for POST, PUT, and DELETE methods as well. These functions can be used to create a new employee and update or delete the employee based on their given ID.

Python
@app.route('/employees', methods=['POST'])
def create_employee():
 global nextEmployeeId
 employee = json.loads(request.data)
 if not employee_is_valid(employee):
 return jsonify({ 'error': 'Invalid employee properties.' }), 400

 employee['id'] = nextEmployeeId
 nextEmployeeId += 1
 employees.append(employee)

 return '', 201, { 'location': f'/employees/{employee["id"]}' }

@app.route('/employees/<int:id>', methods=['PUT'])
def update_employee(id: int):
 employee = get_employee(id)
 if employee is None:
 return jsonify({ 'error': 'Employee does not exist.' }), 404

 updated_employee = json.loads(request.data)
 if not employee_is_valid(updated_employee):
 return jsonify({ 'error': 'Invalid employee properties.' }), 400

 employee.update(updated_employee)

 return jsonify(employee)

@app.route('/employees/<int:id>', methods=['DELETE'])
def delete_employee(id: int):
 global employees
 employee = get_employee(id)
 if employee is None:
 return jsonify({ 'error': 'Employee does not exist.' }), 404

 employees = [e for e in employees if e['id'] != id]
 return jsonify(employee), 200


Once our code is complete, it should look like this:

Python
import json
from flask import Flask, jsonify, request
app = Flask(__name__)

employees = [
 { 'id': 1, 'name': 'Ashley' },
 { 'id': 2, 'name': 'Kate' },
 { 'id': 3, 'name': 'Joe' }
]


nextEmployeeId = 4
3
@app.route('/employees', methods=['GET'])
def get_employees():
 return jsonify(employees)

@app.route('/employees/<int:id>', methods=['GET'])
def get_employee_by_id(id: int):
 employee = get_employee(id)
 if employee is None:
 return jsonify({ 'error': 'Employee does not exist'}), 404
 return jsonify(employee)

def get_employee(id):
 return next((e for e in employees if e['id'] == id), None)

def employee_is_valid(employee):
 for key in employee.keys():
 if key != 'name':
     return False
 return True

@app.route('/employees', methods=['POST'])
def create_employee():
 global nextEmployeeId
 employee = json.loads(request.data)
 if not employee_is_valid(employee):
 return jsonify({ 'error': 'Invalid employee properties.' }), 400

 employee['id'] = nextEmployeeId
 nextEmployeeId += 1
 employees.append(employee)

 return '', 201, { 'location': f'/employees/{employee["id"]}' }

@app.route('/employees/<int:id>', methods=['PUT'])
def update_employee(id: int):
 employee = get_employee(id)
 if employee is None:
 return jsonify({ 'error': 'Employee does not exist.' }), 404

 updated_employee = json.loads(request.data)
 if not employee_is_valid(updated_employee):
 return jsonify({ 'error': 'Invalid employee properties.' }), 400

 employee.update(updated_employee)

 return jsonify(employee)

@app.route('/employees/<int:id>', methods=['DELETE'])
def delete_employee(id: int):
 global employees
 employee = get_employee(id)
 if employee is None:
 return jsonify({ 'error': 'Employee does not exist.' }), 404

 employees = [e for e in employees if e['id'] != id]
 return jsonify(employee), 200

if __name__ == '__main__':
   app.run(port=5000)


Lastly, we will add a line of code to run our Flask app. As you can see, we call the run method and get the Flask app running on port 5000.

Python
if __name__ == '__main__':
 app.run(port=5000)


Running and Testing The Code

With our code written and saved, we can start the app up. To run the app, in the terminal, we will execute the following pip command.

Shell
pip api.py


Now, our API is up and running. You can send a test HTTP request through Postman. By sending a request to localhost:5000/employees. After the request is sent. you should see a 200 OK status code in the response along with an array of employees returned.

For this test, no request body is needed for the incoming request.

Wrapping Up

With that, we’ve created a simple RESTful API Flask using Python. This code can then be expanded on as needed to build APIs for your applications.

API Build (game engine) Flask (web framework) Id (programming language) Python (language) Data Types Python programming language Software development shell

Published at DZone with permission of Preet Kaur. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Beyond Django and Flask: How FastAPI Became Python's Fastest-Growing Framework for Production APIs
  • Build a Simple REST API Using Python Flask and SQLite (With Tests)
  • A Complete API Development Guide: Common Terms, Tools, and Best Practices
  • How to Build a URL Shortener Web App With Flask Framework

Partner Resources

×

Comments

The likes didn't load as expected. Please refresh the page and try again.

Let's be friends: