Building Your First REST API with Flask

Rakesh Kumar R
4 min readJun 3, 2024

--

Creating a RESTful API with Flask is a great way to get started with web development in Python. In this guide, we’ll walk you through setting up a simple RESTful API for managing a collection of books. By the end, you’ll have a working API that can handle creating, reading, updating, and deleting book records.

Before we start coding, we need to set up our development environment.

Ensure you have Python installed on your system. You can download the latest version from [python.org](https://www.python.org/). Verify the installation by running:

python - version

It’s a good practice to use a virtual environment to manage dependencies for your project. Create and activate a virtual environment with the following commands:

python -m venv venv
source venv/bin/activate # On Windows, use `venv\Scripts\activate`

With the virtual environment activated, install Flask using pip:

pip install Flask

Now that our environment is set up, let’s create the Flask application.

Create a project directory and navigate into it. Inside this directory, create the main application file `app.py`.

mkdir my_flask_app
cd my_flask_app
touch app.py

Open `app.py` in your favorite text editor and start by importing Flask and setting up the application:

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

For simplicity, we’ll use a list of dictionaries to store our book data. Add this list to `app.py`:

books = [
{"id": 1, "title": "1984", "author": "George Orwell"},
{"id": 2, "title": "To Kill a Mockingbird", "author": "Harper Lee"}
]

Next, we’ll define the routes and methods for our API. Each route will handle different HTTP methods to perform CRUD operations.

Create an endpoint to retrieve the list of all books:

@app.route('/books', methods=['GET'])
def get_books():
return jsonify(books)

Create an endpoint to retrieve a single book by its ID:

@app.route('/books/<int:book_id>', methods=['GET'])
def get_book(book_id):
book = next((book for book in books if book["id"] == book_id), None)
if book is None:
return jsonify({"error": "Book not found"}), 404
return jsonify(book)

Create an endpoint to add a new book to the list:

@app.route('/books', methods=['POST'])
def add_book():
new_book = request.get_json()
new_book['id'] = len(books) + 1
books.append(new_book)
return jsonify(new_book), 201

Create an endpoint to update an existing book by its ID:

@app.route('/books/<int:book_id>', methods=['PUT'])
def update_book(book_id):
book = next((book for book in books if book["id"] == book_id), None)
if book is None:
return jsonify({"error": "Book not found"}), 404
data = request.get_json()
book.update(data)
return jsonify(book)

Create an endpoint to delete a book by its ID:

@app.route('/books/<int:book_id>', methods=['DELETE'])
def delete_book(book_id):
global books
books = [book for book in books if book["id"] != book_id]
return '', 204

Finally, add the code to run the Flask application:

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

Your complete `app.py` should look like this:

from flask import Flask, request, jsonify

app = Flask(__name__)

books = [
{"id": 1, "title": "1984", "author": "George Orwell"},
{"id": 2, "title": "To Kill a Mockingbird", "author": "Harper Lee"}
]

@app.route('/books', methods=['GET'])
def get_books():
return jsonify(books)

@app.route('/books/<int:book_id>', methods=['GET'])
def get_book(book_id):
book = next((book for book in books if book["id"] == book_id), None)
if book is None:
return jsonify({"error": "Book not found"}), 404
return jsonify(book)

@app.route('/books', methods=['POST'])
def add_book():
new_book = request.get_json()
new_book['id'] = len(books) + 1
books.append(new_book)
return jsonify(new_book), 201

@app.route('/books/<int:book_id>', methods=['PUT'])
def update_book(book_id):
book = next((book for book in books if book["id"] == book_id), None)
if book is None:
return jsonify({"error": "Book not found"}), 404
data = request.get_json()
book.update(data)
return jsonify(book)

@app.route('/books/<int:book_id>', methods=['DELETE'])
def delete_book(book_id):
global books
books = [book for book in books if book["id"] != book_id]
return '', 204

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

With the application code in place, you can now run your Flask app. In your terminal, navigate to the project directory and execute:

python app.py

Your Flask application will start, and you should see output indicating that the server is running on `http://127.0.0.1:5000/`.

You can test the API using tools like curl, Postman, or directly from your browser. Here are some example commands using curl:

Retrieve the list of all books:

curl http://127.0.0.1:5000/books

Retrieve a single book by its ID:

curl http://127.0.0.1:5000/books/1

Add a new book to the collection:

curl -X POST http://127.0.0.1:5000/books -H "Content-Type: application/json" -d '{"title": "New Book", "author": "Author Name"}'

Update an existing book by its ID:

curl -X PUT http://127.0.0.1:5000/books/1 -H "Content-Type: application/json" -d '{"title": "Updated Title", "author": "Updated Author"}'

Delete a book by its ID:

curl -X DELETE http://127.0.0.1:5000/books/1

Congratulations! You’ve built a simple RESTful API using Flask. This tutorial covered the basics of setting up Flask, creating routes, handling different HTTP methods, and managing a collection of resources. From here, you can extend the functionality by integrating a database, adding authentication, and more.

Happy coding!

--

--

Rakesh Kumar R
Rakesh Kumar R

Written by Rakesh Kumar R

0 Followers

Developer and Designer

No responses yet