Flask is a lightweight, easy-to-use web framework for building web applications in Python. One of its most common uses is to create RESTful APIs, which allow different software systems to communicate with each other over the web. In this simple tutorial, we’ll walk you through creating a basic Flask API step by step.
Table of Contents
What is Flask?
Flask is a microframework for Python, which means it provides the tools you need to build web applications but doesn’t come with the extra features that more extensive frameworks like Django offer. This makes it a great choice for smaller applications or APIs where you want to stay lightweight and have full control over the components you use.
Prerequisites
Before you begin, make sure you have:
- Python installed on your system (version 3.6+).
- A basic understanding of Python programming.
- Installed Flask, which you can do by running the following command in your terminal or command prompt:
pip install Flask
Step 1: Setting Up a Basic Flask App
First, let’s start by setting up a simple Flask app. Create a new directory for your project, and inside it, create a Python file, app.py
.
Here’s a basic example:
from flask import Flask
app = Flask(__name__)
@app.route('/')
def hello_world():
return "Hello, World!"
if __name__ == "__main__":
app.run(debug=True)
Explanation
- Flask app instance: We create an instance of the Flask class, which represents our web application.
- Route: The
@app.route('/')
decorator defines the URL (“/”) that the functionhello_world
will respond to. When someone accesses the root URL, it will return “Hello, World!”. - Debug mode: The
debug=True
enables Flask’s debugging features, which makes it easier to identify errors in your code.
To run the app, navigate to your project folder and run:
python app.py
Now, visit http://127.0.0.1:5000/
in your browser, and you should see “Hello, World!” displayed.
Step 2: Creating a Basic Flask API
Now that we have a basic Flask app up and running, let’s extend it to include a simple API. For this, we’ll create a new route that responds to an HTTP request with JSON data.
Here’s how you can modify your app.py
file:
from flask import Flask, jsonify
app = Flask(__name__)
@app.route('/')
def hello_world():
return "Hello, World!"
@app.route('/api/data', methods=['GET'])
def get_data():
data = {
"message": "Welcome to my API",
"success": True
}
return jsonify(data)
if __name__ == "__main__":
app.run(debug=True)
Explanation
jsonify
: Thejsonify()
function converts a Python dictionary into a JSON response. This is essential for creating an API, as APIs typically exchange data in JSON format.- API route: We’ve created a new route
/api/data
that will respond toGET
requests by returning JSON data with a message and success status.
To test this, restart your Flask app and go to http://127.0.0.1:5000/api/data
in your browser. You should see something like this:
{
"message": "Welcome to my API",
"success": true
}
Step 3: Handling POST Requests
APIs often need to handle various types of requests, such as POST
, which is commonly used to send data to the server. Let’s extend our Flask API to accept POST
requests.
Modify your app.py
as follows:
from flask import Flask, jsonify, request
app = Flask(__name__)
@app.route('/')
def hello_world():
return "Hello, World!"
@app.route('/api/data', methods=['GET'])
def get_data():
data = {
"message": "Welcome to my API",
"success": True
}
return jsonify(data)
@app.route('/api/data', methods=['POST'])
def post_data():
posted_data = request.get_json() # Get the posted JSON data
name = posted_data.get('name')
response = {
"message": f"Hello, {name}",
"success": True
}
return jsonify(response)
if __name__ == "__main__":
app.run(debug=True)
Explanation
request.get_json()
: This function retrieves the JSON data sent in the body of thePOST
request.- Dynamic response: We extract the
name
from the posted data and return a personalized message.
To test the POST
request, you can use a tool like Postman or curl
:
curl -X POST http://127.0.0.1:5000/api/data -H "Content-Type: application/json" -d '{"name":"John"}'
You should receive a JSON response like this:
{
"message": "Hello, John",
"success": true
}
Step 4: Error Handling
It’s important to handle errors in your API to provide clear responses when things go wrong. Let’s add some basic error handling.
Here’s how you can update your post_data
function to include error handling:
@app.route('/api/data', methods=['POST'])
def post_data():
posted_data = request.get_json()
if not posted_data or 'name' not in posted_data:
return jsonify({
"message": "Invalid input",
"success": False
}), 400 # 400 is the HTTP status code for "Bad Request"
name = posted_data.get('name')
response = {
"message": f"Hello, {name}",
"success": True
}
return jsonify(response)
Explanation
- Input validation: We check if the
name
key exists in the posted data. If not, we return an error message with a400
status code. - Error response: The
jsonify()
function is also used to send error responses, maintaining consistency in your API’s response format.
Step 5: Running Your Flask API
At this point, you have a fully functional Flask API that can handle both GET
and POST
requests, along with basic error handling.
To run the API, simply execute:
python app.py
Your API will be live at http://127.0.0.1:5000/
, and you can interact with it using a browser or API testing tools.
Conclusion
In this tutorial, we covered the basics of creating a simple API using Flask. We started by setting up a basic Flask application, added API routes, handled both GET
and POST
requests, and incorporated basic error handling. Flask’s simplicity and flexibility make it an excellent choice for building APIs in Python, especially when you want to keep things lightweight.
By following this guide, you’ve now built your own Flask API and are ready to explore more advanced features such as authentication, database integration, and deploying your API to a live server.
FAQs
1. How do I handle errors in Flask API?
@app.errorhandler()
decorator. This allows you to return specific error messages and status codes for different types of errors.2. How can I test my Flask API?
unittest
framework along with Flask’s testing utilities such as FlaskClient
.3. How do I add authentication to a Flask API?
4. What is Flask-RESTful?
5. How do I handle JSON data in Flask APIs?
request
object. To parse JSON data from a request, use request.get_json()
, and to return JSON data, use jsonify()
from the flask
module.