Hey there, future web maestros! 🎶
Today we’re diving into the nuts and bolts of web interactions: HTTP methods. Don’t let the term scare you—it’s just a fancy way of saying “how browsers and servers talk to each other.” By the end of this guide, you’ll know how to use different HTTP methods to build a more interactive Flask app.
What Are HTTP Methods?
Imagine you’re at a restaurant. You can perform various actions like ordering food, asking for the bill, or canceling an order. In the world of web apps, these actions are akin to HTTP methods. The most commonly used methods are GET, POST, PUT, and DELETE.
The GET Method
Think of the GET method like asking for a menu in a restaurant. You’re asking the server to give you something, like a webpage or some data.
In Flask, a simple GET request can be handled like this:
@app.route('/menu') def menu(): return "Here's the menu!"
The POST Method
When you order food, you’re asking the server to do something with the information you provided. In HTTP terms, you’re making a POST request.
Here’s how you can handle a POST request in Flask:
@app.route('/order', methods=['POST']) def order(): item = request.form['item'] return f'You ordered {item}.'
The PUT and DELETE Methods
PUT and DELETE are like updating or canceling an order. PUT modifies existing data, and DELETE removes it.
Here’s a quick example in Flask:
@app.route('/update_order/<int:order_id>', methods=['PUT']) def update_order(order_id): # code to update order return f'Order {order_id} updated.' @app.route('/cancel_order/<int:order_id>', methods=['DELETE']) def cancel_order(order_id): # code to delete order return f'Order {order_id} deleted.'
Practical Example: A Simple CRUD Application with Lists
In this example, we’ll use a Python list to store book data. Each book will be a dictionary with fields like id, title, and author.
Initialize Book List
First, let’s initialize a list that will act as our temporary database:
books = [] book_id = 0 # This will act as our unique identifier for each book
Create a Book (POST)
To add a book, we’ll increment the book_id and append a new dictionary to the books list:
@app.route('/add_book', methods=['POST']) def add_book(): global book_id title = request.form['title'] author = request.form['author'] book_id += 1 books.append({'id': book_id, 'title': title, 'author': author}) return f'Added {title} by {author}.'
Read Books (GET)
To fetch all books, we’ll simply return the books list:
@app.route('/books', methods=['GET']) def get_books(): return str(books)
Update a Book (PUT)
To update a book, we’ll search for it by id in the books list and update its fields:
@app.route('/update_book/<int:book_id>', methods=['PUT']) def update_book(book_id): for book in books: if book['id'] == book_id: book['title'] = request.form['title'] book['author'] = request.form['author'] return f'Book {book_id} updated.' return 'Book not found.'
Delete a Book (DELETE)
To delete a book, we’ll find it by id and remove it from the books list:
@app.route('/delete_book/<int:book_id>', methods=['DELETE']) def delete_book(book_id): global books books = [book for book in books if book['id'] != book_id] return f'Book {book_id} deleted.'
Let’s convert our knowledge and the example discussed above into a mini-project.
Project Structure
- mini_bookstore/ - templates/ - index.html - add_book.html - app.py
To try this mini-project:
- Create a folder called `mini_bookstore`.
- Inside it, create a folder called `templates`.
- Create the Python file `app.py` and the HTML files `index.html` and `add_book.html` with the provided code.
`app.py`
Here’s the Python code that makes up the Flask application:
from flask import Flask, render_template, request, redirect, url_for app = Flask(__name__) # Initialize book list and book ID books = [] book_id = 0 @app.route('/') def index(): return render_template('index.html', books=books) @app.route('/add_book', methods=['GET', 'POST']) def add_book(): global book_id if request.method == 'POST': title = request.form['title'] author = request.form['author'] book_id += 1 books.append({'id': book_id, 'title': title, 'author': author}) return redirect(url_for('index')) return render_template('add_book.html') @app.route('/update_book/<int:book_id>', methods=['POST']) def update_book(book_id): for book in books: if book['id'] == book_id: book['title'] = request.form['new_title'] book['author'] = request.form['new_author'] return redirect(url_for('index')) return 'Book not found.' @app.route('/delete_book/<int:book_id>', methods=['POST']) def delete_book(book_id): global books books = [book for book in books if book['id'] != book_id] return redirect(url_for('index')) if __name__ == '__main__': app.run(debug=True)
`templates/index.html`
This HTML file will display the list of books and provide options to add or delete books.
<!DOCTYPE html> <html> <head> <title>Mini Bookstore</title> </head> <body> <h1>Mini Bookstore</h1> <a href="{{ url_for('add_book') }}">Add Book</a> <ul> {% for book in books %} <li> {{ book['title'] }} by {{ book['author'] }} <!-- Delete button --> <form action="{{ url_for('delete_book', book_id=book['id']) }}" method="post" style="display: inline;"> <input type="submit" value="Delete"> </form> <!-- Update form --> <form action="{{ url_for('update_book', book_id=book['id']) }}" method="post" style="display: inline;"> <input type="text" name="new_title" placeholder="New title"> <input type="text" name="new_author" placeholder="New author"> <input type="submit" value="Update"> </form> </li> {% endfor %} </ul> </body> </html>
`templates/add_book.html`
This HTML file will display a form to add a new book.
<!DOCTYPE html> <html> <head> <title>Add Book</title> </head> <body> <h1>Add Book</h1> <form action="{{ url_for('add_book') }}" method="post"> <label for="title">Title:</label> <input type="text" id="title" name="title" required><br> <label for="author">Author:</label> <input type="text" id="author" name="author" required><br> <input type="submit" value="Add Book"> </form> <a href="{{ url_for('index') }}">Back to Book List</a> </body> </html>
To run the project, navigate to the mini_bookstore folder in your terminal and execute:
flask run
Visit http://127.0.0.1:5000/ in your browser to interact with your mini-bookstore.
Conclusion
And there you have it! You’ve built a simple CRUD application using Flask and Python lists. Though this isn’t how you’d manage data in a production application, it’s a great way to understand CRUD operations without the complexity of databases.
In the next blog post, we’ll upgrade from using lists to using a real database, so you can see how data management is done in larger applications.