DEV Community

Shawn Smith
Shawn Smith

Posted on

Building an API in Flask

Flask is a popular web framework for building web applications and APIs in Python. It is known for its simplicity, flexibility, and ease of use. Flask allows developers to create web applications and APIs quickly and easily, without sacrificing performance or functionality.

In this blog, we will explore how to build APIs in Flask. We will cover the basics of Flask, including how to install and set up Flask, how to create routes, and how to handle HTTP requests and responses.

Setting Up Flask
Before we can start building our API, we need to install Flask. We can do this using pip, the Python package manager. Open up a terminal and enter the following command:

pip install flask

Once Flask is installed, we can start building our API.

Creating a Simple Flask App
Let's start by creating a simple Flask app. Open up a new Python file and import Flask:

from flask import Flask

app = Flask(__name__)

Enter fullscreen mode Exit fullscreen mode

This creates a new Flask app. We also created a new instance of the Flask class and stored it in the app variable.

Next, let's create a route that returns a simple message:

@app.route('/')
def hello():
    return 'Hello, World!'

Enter fullscreen mode Exit fullscreen mode

This code defines a new route that listens to the root URL (/). When a client makes a request to this URL, Flask will execute the hello() function and return the message "Hello, World!".

Finally, let's run the app:

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

Enter fullscreen mode Exit fullscreen mode

This code starts the Flask app and runs it in debug mode. We can now run the app by running this Python file.

Handling HTTP Requests
Flask makes it easy to handle HTTP requests. Let's create a new route that handles a GET request and returns some data:

from flask import request

@app.route('/data', methods=['GET'])
def get_data():
    data = {'name': 'John', 'age': 30}
    return data

Enter fullscreen mode Exit fullscreen mode

In this code, we define a new route /data that listens to GET requests. When a client makes a GET request to this URL, Flask will execute the get_data() function and return the dictionary {'name': 'John', 'age': 30}.

Note that we imported request from Flask. This allows us to access information about the HTTP request, such as its method and parameters.

Handling HTTP Responses
Flask also makes it easy to handle HTTP responses. Let's modify our previous example to return a JSON response:

from flask import jsonify

@app.route('/data', methods=['GET'])
def get_data():
    data = {'name': 'John', 'age': 30}
    return jsonify(data)

Enter fullscreen mode Exit fullscreen mode

In this code, we imported jsonify from Flask. This function takes a Python dictionary as an argument and returns a JSON-encoded response.

Error Handling
Flask also makes it easy to handle errors. Let's create a new route that throws an error:

@app.route('/error')
def throw_error():
    raise Exception('Something went wrong')

Enter fullscreen mode Exit fullscreen mode

In this code, we define a new route /error that throws an exception. When a client makes a request to this URL, Flask will execute the throw_error() function and raise an exception.

We can handle this exception by creating an error handler:

@app.errorhandler(Exception)
def handle_error(e):
    return 'An error occurred: ' + str(e), 500

Enter fullscreen mode Exit fullscreen mode

In this code, we define an error handler that handles all exceptions. When an exception is raised, Flask will execute the handle_error() function and return an error message with the exception.

Top comments (0)