Navaratri Upgrade your projects this Navaratri! Flat 20% off on all Django, Symfony, and Laravel applications.
Purchase Now

  • Login
Website Logo
  • Home
  • Projects
  • Courses
  • Contact
  • Blog
  • Client Services
  • Our Portfolio
Join Now

Course Category

  • Python
  • React Js
  • Django
    • Python Django Tutorial: Build a Comprehensive Student Management System | Python Projects & Django in Hindi
    • Master Django: Build a High-Performance Blog Website from Scratch 📝💻
  • Symfony
  • Laravel
  • Node Js
  • JavaScript
  • Bootstrap
  • Sylius
  • Wordpress
  • HTML5
  • CSS3
Learn More
Education Logo Images

At WebifyDev, we believe that great things happen when talented and motivated individuals come together.

  • example@gmail.com
  • (302) 555-0107
  • Home
  • Courses
  • About Us
  • Contact
  • Blog
  • Faqs
  • Privacy Policy
Enroll Now
Find With Us
Education Images
  • blog-image
    Dev Patel in Python
  • 29 Oct 2024

How to Build a Simple REST API with Python and Flask

Learn how to create a simple REST API using Python and Flask. This guide covers the basics of setting up Flask, creating API routes, and testing your API endpoints.

How to Build a Simple REST API with Python and Flask
Building REST APIs with Python and Flask – Seamless Communication between Systems through Efficient Endpoints

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!

Python
blog-image
Dev
Author

👨‍💻 Dev Patel | Software Engineer 🚀 | Passionate about crafting efficient code, optimizing systems, and building user-friendly digital experiences! 💡

0 Comments

  • No comments yet. Be the first to comment!

Leave a Comment

Related Post

Similar Post

What is the Django Framework and Its Uses
What is the Django Framework and Its Uses
Read Article
Getting Started with Python Django: A Comprehensive Beginner's Guide
Getting Started with Python Django: A Comprehensive Beginner's Guide
Read Article
Python for Data Analysis: A Beginner’s Guide to Pandas and NumPy
Python for Data Analysis: A Beginner’s Guide to Pandas and NumPy
Read Article
WebifyDev Logo

At WebifyDev, we believe that great things happen when talented and motivated individuals come together.

Contact With Us
Useful Links
  • Home
  • My Account
  • Dashboard
  • Courses
  • Blog
  • Our Portfolio
  • Lucky Draw
Our Company
  • About
  • Contact Us
  • Client Services
  • Privacy Policy
  • Terms of Service
  • Cancellation & Refund Policy
  • Shipping Policy
  • Faqs
Get Contact
  • E-mail: webifydev.team@gmail.com
  • Address: Swarnim Dharti, Ahmedabad, Gujarat 382421

Copyright © 2025 WebifyDev. All Rights Reserved.

  • Privacy Policy
  • Login & Register