DEV Community

Cover image for Building APIs with Flask: What They Are and What They’re Used For
Jasec
Jasec

Posted on

Building APIs with Flask: What They Are and What They’re Used For

What is an API?

An API (Application Programming Interface) allows software systems to communicate, share data, and work together.

A common analogy for APIs is a restaurant setting: the customer (client) places an order (request) with the waitress, the waitress sends the order to the chef (server), the chef prepares the food and sends it back (response), and finally the customer receives the meal.

APIs are useful because they make development more efficient by providing functionality that already exists. This allows developers to reuse existing APIs instead of building everything from scratch, and it also helps applications scale as they grow.

How do APIs function?

APIs generally work through a sequence of four steps: request, processing, response, and delivery. In this section, we will focus on the request and response phases.

Request

APIs use different HTTP methods to define the type of action being performed.

GET

Used to retrieve data from a specific resource.

POST

Used to send data to the server to create a new resource.

PUT

Used to create or fully update a resource. Unlike POST, PUT requests produces the same result every time.

produce the same result even when the same request is sent multiple times

PATCH

Used to apply partial updates to an existing resource.

DELETE

Used to remove a specific resource from the server.

Response

A response is what the server sends back after processing a request, allowing the frontend to update the UI. In the response we usually find:

  • Data in JSON format.
  • An HTTP status code (200 OK, 201 Created, 204 No Content, 404 Not Found).

In Flask, building APIs consists of defining routes that manage these requests and retrieve JSON responses to the client.

How are APIs built in Flask

Flask is a Python framework that helps build web servers and define API endpoints. It also allows developers to implement RESTful APIs by mapping URLs and HTTP methods to Python functions.

To start a Flask application, a Flask application instance must be created. This instance represents the web application and it is responsible for handling incoming requests and routing them to the appropriate functions.


from flask import Flask

app = Flask(__name__)

@app.route('/')
def index():
    return '<h1>Welcome to Manga Hub!</h1>'

@app.route('/<string:naruto>')
def character(naruto):
    return f'<h1>This is {naruto}</h1>'

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

Enter fullscreen mode Exit fullscreen mode

In this example, Flask is imported and an instance of the Flask class is created. The __ name __ argument helps Flask determine where the application’s files can be located.

When a client sends a request to the server, Flask receives the request and tries to match it to a route. Routes associate URLs with Python functions, allowing the application to determine which function should handle a specific request.

The @app.route() decorator maps a URL to a function. In this case, the index() function is executed when the root route ("/") is requested, and the character() function is executed when a dynamic URL is accessed.

The function associated with the ("/") route is usually called a view. A view represents the response that is sent back to the client after a request is made. In this case, the function returns a simple HTML string, <h1>Welcome to Manga Hub!</h1>, which is then displayed to the user.

Another important detail in route decorators is that anything passed between the angle brackets (<>) must be used as a parameter in the function. This also allows us to validate the data type of the parameter.

After analyzing how routes and endpoints work in Flask, the next example demonstrates how a POST method processes incoming data and returns a JSON response.

Example:

Flask Restful

We can observe that the application starts with a decorator (@app.route("/")) that returns a string as a sanity check. After that, we see the Mangas class. By using Flask-RESTful, we can define a resource class, which allows us to group related behaviors into a single block instead of creating multiple decorators for each endpoint.

Inside the Mangas class, a get() method is defined to retrieve all mangas. We also see a post() method that receives incoming data using request.get_json(). The data is then validated, used to create a new manga object, and finally added and committed to the database.

After execution, the server returns a JSON object along with a status code of 201, using make_response().

jsonify() vs make_response()

Flask-RESTful automatically converts Python dictionaries and lists into JSON responses. For this reason, make_response() is used in the example above, since it allows explicit control over the HTTP status code. In plain Flask applications, it is very common to use jsonify() to manually convert responses into JSON.

Note: In this example, the Resource and API classes are used. By creating an instance of the API class and combining it with a resource, HTTP methods can be defined without manually checking the request method using conditionals. Under the hood, the API instance creates a route using
api.add_resource(Mangas, "/mangas"), inspects the resource class, and maps each HTTP method to the appropriate function.

Conclusion

In conclusion, APIs are used everywhere today and represent a fundamental part of modern software development.

Top comments (0)