In this tutorial, we will learn how to build REST APIs using Flask, a lightweight and powerful web framework for Python.
By the end of this tutorial, you will understand what REST APIs are and how to create them using Flask. You will also learn how to use HTTP methods in Flask, how to process JSON data, and how to handle requests and responses.
You will need a basic understanding of Python and JSON. Experience with Flask or web development is not necessary, but it would be helpful.
REST (Representational State Transfer) is a standard for designing network applications. A REST API uses HTTP to perform operations (like GET, POST, PUT, DELETE) on data.
First, you need to install Flask. You can do this with pip:
pip install flask
To create a Flask app, you need to import Flask and create an instance of the Flask class:
from flask import Flask
app = Flask(__name__)
In Flask, you can define routes using the @app.route()
decorator and a function that returns the response:
@app.route('/')
def hello():
return "Hello, World!"
You can run the Flask app with app.run()
:
if __name__ == '__main__':
app.run(debug=True)
The debug=True
argument enables debug mode, which shows detailed error messages if something goes wrong.
Now let's create a simple REST API for managing books. We'll use a list of dictionaries to store our books for simplicity.
from flask import Flask, jsonify, request
app = Flask(__name__)
books = [
{'id': 1, 'title': 'The Great Gatsby', 'author': 'F. Scott Fitzgerald'},
{'id': 2, 'title': '1984', 'author': 'George Orwell'},
{'id': 3, 'title': 'To Kill a Mockingbird', 'author': 'Harper Lee'},
]
@app.route('/books', methods=['GET'])
def get_books():
return jsonify({'books': books})
@app.route('/books', methods=['POST'])
def add_book():
book = {'id': len(books) + 1, 'title': request.json['title'], 'author': request.json['author']}
books.append(book)
return jsonify({'book': book}), 201
@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': 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)
We've learned how to create a REST API with Flask, how to define routes, and how to handle different HTTP methods. We also learned how to process JSON data and how to use the jsonify
function to convert Python objects to JSON.
Add a PUT method to the /books/<int:book_id>
route to update a book's title and author. Test your API with curl or Postman.
Create a REST API for another type of data, like movies or songs. Include at least the GET, POST, and DELETE methods.
Add error handling to your API. For example, what should happen if someone tries to add a book without a title or author, or tries to update a book that doesn't exist?
Remember, practice is the key to mastering any skill, so make sure you experiment and try different things with your API. Happy coding!