DEV Community

Diwakar kothari
Diwakar kothari

Posted on

flaaskkkk hidevs

Creating a RESTful API with Flask: GET and POST Methods

In this article, we'll explore how to create a RESTful API using the Flask web framework in Python. We'll focus on two essential HTTP methods: GET and POST.

Prerequisites

Before you start, make sure you have the following installed:

  • Python: You'll need Python installed on your system.
  • Flask: You can install Flask using pip install Flask.

Setting Up Your Flask Application

Start by creating a new directory for your project and a Python file (e.g., app.py) to hold your Flask application.

# Import the Flask module
from flask import Flask, request, jsonify

# Create a Flask app
app = Flask(__name__)

# Dummy data for demonstration
data = []

# Define a route for the root URL
@app.route('/')
def hello_world():
    return "Hello, World!"

# GET Method
@app.route('/api/data', methods=['GET'])
def get_data():
    return jsonify(data)

# POST Method
@app.route('/api/data', methods=['POST'])
def add_data():
    new_item = request.json  # Get JSON data from the request body
    data.append(new_item)   # Append data to the list
    return jsonify({"message": "Data added successfully!"})

if __name__ == '__main__':
    app.run(debug=True) 
Enter fullscreen mode Exit fullscreen mode

Top comments (0)