
How to Build a Simple REST API with Python and Flask
REST APIs are a fundamental part of modern web development, allowing different systems to communicate with each other. Python, combined with the Flask framework, makes it easy to create simple and efficient REST APIs.
In this guide, we’ll walk through how to set up Flask and build a basic REST API with CRUD (Create, Read, Update, Delete) operations.
1. Prerequisites
Before we begin, make sure you have Python installed. You can install Flask using pip:
# Install Flask
pip install Flask
2. Setting Up Your Flask App
Let’s create a new Flask app by following these steps:
# Create a file named app.py and add the following code:
from flask import Flask, jsonify, request
app = Flask(__name__)
@app.route('/')
def home():
return "Welcome to the Flask REST API!"
if __name__ == '__main__':
app.run(debug=True)
Run the app using python app.py
and open http://127.0.0.1:5000/
in your browser. You should see the message: “Welcome to the Flask REST API!”
3. Creating API Routes
Now, let’s define some basic API routes to perform CRUD operations. We’ll use a dictionary to store our data temporarily.
# Define some sample data
books = [
{'id': 1, 'title': 'Python Basics', 'author': 'Alice'},
{'id': 2, 'title': 'Flask Essentials', 'author': 'Bob'}
]
# Get all books
@app.route('/books', methods=['GET'])
def get_books():
return jsonify(books)
# Get a specific book by ID
@app.route('/books/', methods=['GET'])
def get_book(book_id):
book = next((b for b in books if b['id'] == book_id), None)
return jsonify(book) if book else {'error': 'Book not found'}, 404
# Add a new book
@app.route('/books', methods=['POST'])
def add_book():
new_book = request.get_json()
books.append(new_book)
return jsonify(new_book), 201
4. Testing Your API Endpoints
With the above routes defined, you can test your API using a tool like Postman or Python’s requests
library:
# Example using Python's requests library
import requests
response = requests.get('http://127.0.0.1:5000/books')
print(response.json())
5. Updating and Deleting Data
Let’s add routes for updating and deleting books:
# Update a book
@app.route('/books/', methods=['PUT'])
def update_book(book_id):
updated_data = request.get_json()
for book in books:
if book['id'] == book_id:
book.update(updated_data)
return jsonify(book)
return {'error': 'Book not found'}, 404
# Delete a book
@app.route('/books/', methods=['DELETE'])
def delete_book(book_id):
global books
books = [b for b in books if b['id'] != book_id]
return {'message': 'Book deleted'}
6. Conclusion
Congratulations! You’ve just built a simple REST API using Python and Flask. You can further expand this API by connecting it to a database, adding authentication, or deploying it to a cloud service. Flask provides a lightweight and flexible way to create web services that can be easily integrated into larger applications.
Happy coding!
0 Comments