Top Ad unit 728 × 90

Welcome !!! To The World of Programming

OOPS FEATURES

Oops

Flask REST API + MySQL User Authentication API

 Flask REST API Authentication - MySQL + JWT Step-by-Step

What is a Service?

A service is a self-contained unit of functionality that performs specific tasks and provides reusable operations. Services are commonly used in distributed computing and microservices architectures to allow different applications to communicate with each other.

Types of Services:

Web Services – Services accessible over the web (e.g., REST, SOAP).

Microservices – Small, independent services handling different functionalities (e.g., authentication, payment).

Cloud Services – Services hosted on cloud platforms like AWS, Azure.

What is a RESTful API?

A RESTful API (Representational State Transfer API) is a web service that follows REST principles and allows communication between clients (e.g., frontend apps) and servers.

REST Principles:

Client-Server Architecture – The client (frontend) and server (backend) are separate.

Stateless – The server does not store client session (State Management) data.

Cacheable – Responses can be cached for performance.

Uniform Interface – Uses standard HTTP methods (GET, POST, PUT, DELETE).

      Layered System – Can have multiple layers like authentication, load balancing.

How Does a RESTful API Work?

A RESTful API exposes endpoints (URLs) to allow clients (websites, mobile apps) to perform operations on

resources.

Method Operation Example Endpoint Description
Get

Read

/users

Retrieve all users

Get

Read

/users/1

Retrieve user with ID 1

Post

Create

/users

Add a new user

Put

Update

/users/1

Update user with ID 1

Delete

Delete

/users/1

Remove user with ID 1


Common HTTP Status Codes in RESTful APIs:

Code

Used For

200 OK

Successful GET, POST, PUT, or DELETE request.

201 Created

When a new resource is successfully created (POST).

400 Bad Request

When request data is invalid or malformed.

401 Unauthorized

If authentication is missing or incorrect.

403 Forbidden

When the user is not allowed to access a resource.

404 Not Found

When the requested resource does not exist.

500 Internal Server Error

When something goes wrong on the server.


JWT Token (JSON Web Token):

A JWT (JSON Web Token) is a compact, URL-safe token used to securely transmit information between two parties — typically the client and the server.

How It Works in Your App?

User Logs In → Server verifies credentials.

Server Returns JWT → Client stores it (usually in localStorage or a cookie).

Client Sends JWT in the Authorization header on future requests:  Authorization: Bearer <token>

Server Verifies JWT using the secret key, and lets the request through.

What is Postman?

Postman is a popular API development and testing tool.

It is used by developers to design, test, document, and monitor APIs (Application Programming Interfaces).

It provides a user-friendly interface to send HTTP requests (like GET, POST, PUT, DELETE) and

analyze responses without writing code manually.

Implementing a Simple RESTful API using Flask:

Let’s implement a simple RESTful API using Flask for user registration, login, and role-based access control. The system defines four endpoints: register, login, dashboard, and admin_panel, demonstrating secure access with JWT authentication and role verification.

Create Database 'SamplDB' and table user:

CREATE TABLE users (

         id INT AUTO_INCREMENT PRIMARY KEY,

         username VARCHAR(50) UNIQUE NOT NULL,

         password VARCHAR(200) NOT NULL,

         role ENUM('user', 'admin') DEFAULT 'user',

         approved BOOLEAN DEFAULT FALSE

);

Endpoint

Endpoint

Endpoint

Endpoint

/register

POST

Register a new user with username, password, and role.

Public

/login

POST

Authenticate user and return JWT token.

Public

/dashboard

GET

Access protected user dashboard.

Authenticated users (User/Admin)

/admin_panel

GET

Access protected admin dashboard.

Authenticated Admin only

The required Python code is as follows:

from werkzeug.security import generate_password_hash, check_password_hash
from flask import Flask, request, jsonify
from flask_jwt_extended import JWTManager, create_access_token, jwt_required, get_jwt, get_jwt_identity
import mysql.connector
app = Flask(__name__)
app.config['JWT_SECRET_KEY'] = 'testapi'

jwt = JWTManager(app)

# MySQL DB connection setup
db = mysql.connector.connect(
    host="localhost",
    user="root",
    password="",
    database="sampledb"
)
cursor = db.cursor(dictionary=True)
@app.route('/register', methods=['POST'])
def register():
    data = request.get_json()
    
    username = data.get('username')
    password = data.get('password')

    if not username or not password:
        return jsonify({'error': 'Missing username or password'}), 400

    cursor = db.cursor(dictionary=True)
    cursor.execute("SELECT * FROM users WHERE username=%s", (username,))
    existing_user = cursor.fetchone()

    if existing_user:
        return jsonify({'error': 'User already exists'}), 409
    password_hash = generate_password_hash(password)
    cursor.execute("INSERT INTO users (username, password) VALUES (%s, %s)", (username, password_hash))
    db.commit()

    return jsonify({'message': 'User registered successfully'}), 201

@app.route('/login', methods=['POST'])
def login():
    data = request.get_json()
    username = data.get("username")
    password = data.get("password")
    
    cursor.execute("SELECT username, password, role, approved FROM users WHERE username = %s", (username,))
    user = cursor.fetchone()
    if not user:
        return jsonify({"error": "Invalid User"}), 403

    if not user['approved']:
        #print(user['password'])
        return jsonify({"error": "Account not approved by admin"}), 403
    if user and check_password_hash(user['password'], password):
        # Generate JWT Token
        token = create_access_token(identity=username, additional_claims={"role": user["role"]})

        return jsonify({"access_token": token}), 200
    else:
        #print("Here")
        return jsonify({"error": "Invalid credentials"}), 401
          

@app.route('/dashboard', methods=['GET'])
@jwt_required()
def dashboard():
    identity = get_jwt_identity()
    username = identity
    print(username)
    return jsonify(message=f"Welcome, {username}!"), 200

@app.route('/admin', methods=['GET'])
@jwt_required()
def admin_panel():
    claims = get_jwt()
    if claims.get('role') != 'admin':
        return jsonify({"error": "Admins only"}), 403

    return jsonify({"message": "Welcome to the admin panel!"})

if __name__ == '__main__':
    app.run(debug=True)


Benefits of RESTful API Services:

Scalability:     RESTful APIs are stateless. Each request contains all information needed, allowing the server to scale easily (add more servers without maintaining session state).

Simplicity:      REST uses simple HTTP methods (GET, POST, PUT, DELETE). Easy for developers to understand and integrate with. No complex protocols.

Flexibility and Portability:   REST APIs can be consumed by any client (browser, mobile app, IoT device) using any language (Python, JavaScript, etc.).

Performance Optimization:  REST APIs can use HTTP caching to reduce server load and improve response times. Responses can be optimized using lightweight formats like JSON.

Statelessness:  Each request from a client contains all information needed. No server memory of previous requests, making error recovery and server restarts simpler.

Layered System:        APIs can be organized in layers (e.g., Authentication Layer, Business Logic Layer, Database Layer), improving modularity and scalability.

Standardized Communication:        REST APIs use standard HTTP status codes, headers, and methods — making them predictable and interoperable across systems.

Easy Integration:       REST APIs are commonly used across cloud services, third-party applications, and microservices architecture — making integration seamless.

Maintainability:         Clear separation between client and server enables independent updates to either side without breaking the other.










Flask REST API + MySQL User Authentication API Reviewed by Syed Hafiz Choudhary on May 07, 2025 Rating: 5

No comments:

Contact Form

Name

Email *

Message *

Powered by Blogger.
!-- JavaScript for Ad Block Detection -->