REST API with Flask in Python
About the project: This is a simple REST API project using the Flask framework, all contained within a single, self-contained Python file.
This project will demonstrate the fundamental principles of a RESTful API by creating a simple endpoint to manage a collection of books.
You can perform common actions like retrieving all books, getting a specific book, adding a new book, and updating or deleting an existing one.
Instructions
- Install Flask: This project requires the Flask library. You'll need to install it first if you don't have it already.
pip install Flask
- Save the Code: Save the code below as a file named rest_api.py.
- Run the App: Open your terminal or command prompt, navigate to the directory where you saved the file, and run the script:
python rest_api.py
- Access the API: The API will be running at http://127.0.0.1:5000. You can use tools like curl or a browser extension like Postman to interact with the endpoints.
This project provides a solid foundation for building more complex APIs.
If you'd like to extend this, you could explore adding a real database, incorporating user authentication, or even adding a front-end to interact with it.
Project Level: Intermediate
You can directly copy the below snippet code with the help of green copy button, paste it and run it in any Python editor you have.
Steps: Follow these stepsStep 1: Copy below code using green 'copy' button.
Step 2: Paste the code on your chosen editor.
Step 3: Save the code with filename and .py extention.
Step 4: Run (Press F5 if using python IDLE).
# rest_api.py
from flask import Flask, jsonify, request
# Initialize the Flask application
app = Flask(__name__)
# A simple list of dictionaries to act as our in-memory database
# In a real-world application, this would be a database like PostgreSQL or MongoDB
books = [
{
'id': 1,
'title': 'The Lord of the Rings',
'author': 'J.R.R. Tolkien',
'published': 1954
},
{
'id': 2,
'title': 'Dune',
'author': 'Frank Herbert',
'published': 1965
},
{
'id': 3,
'title': 'Foundation',
'author': 'Isaac Asimov',
'published': 1951
}
]
# --- API Endpoints ---
@app.route('/books', methods=['GET'])
def get_all_books():
"""
Handles GET requests to retrieve the list of all books.
Returns:
A JSON object containing the list of books.
"""
return jsonify({'books': books})
@app.route('/books/', methods=['GET'])
def get_book_by_id(book_id):
"""
Handles GET requests to retrieve a single book by its ID.
Args:
book_id (int): The ID of the book to retrieve.
Returns:
A JSON object for the book if found, otherwise an error message.
"""
book = next((book for book in books if book['id'] == book_id), None)
if book:
return jsonify({'book': book})
else:
# Return a 404 Not Found error if the book is not in the list
return jsonify({'error': 'Book not found'}), 404
@app.route('/books', methods=['POST'])
def add_new_book():
"""
Handles POST requests to add a new book to the list.
The request must contain a JSON body with 'title' and 'author'.
Returns:
A JSON object for the newly created book.
"""
# Check if the request body is valid JSON
if not request.json or 'title' not in request.json or 'author' not in request.json:
return jsonify({'error': 'Invalid request format. Must contain title and author.'}), 400
new_book = {
'id': books[-1]['id'] + 1 if books else 1,
'title': request.json['title'],
'author': request.json['author'],
'published': request.json.get('published') # 'published' is optional
}
books.append(new_book)
# Return a 201 Created status code
return jsonify({'book': new_book}), 201
@app.route('/books/', methods=['PUT'])
def update_book(book_id):
"""
Handles PUT requests to update an existing book by its ID.
The request must contain a JSON body with the fields to update.
Returns:
A JSON object for the updated book.
"""
book = next((book for book in books if book['id'] == book_id), None)
if not book:
return jsonify({'error': 'Book not found'}), 404
# Update the book with any fields provided in the request
if 'title' in request.json:
book['title'] = request.json['title']
if 'author' in request.json:
book['author'] = request.json['author']
if 'published' in request.json:
book['published'] = request.json['published']
return jsonify({'book': book})
@app.route('/books/', methods=['DELETE'])
def delete_book(book_id):
"""
Handles DELETE requests to remove a book from the list by its ID.
Returns:
A confirmation message.
"""
book = next((book for book in books if book['id'] == book_id), None)
if not book:
return jsonify({'error': 'Book not found'}), 404
books.remove(book)
return jsonify({'message': 'Book deleted successfully'})
# Run the application
if __name__ == '__main__':
# Setting debug=True reloads the server automatically on code changes
# It should be set to False in a production environment
app.run(debug=True, host='0.0.0.0', port=5000)
← Back to Projects