Flask Rest API With User Signup&Login with JWT Token

Flask Rest API With User Signup&Login with JWT Token

Introduction:

The ocean of web development is an exciting world, especially when you have knowledge of strong tools such as Flask – a Python micro-framework for web application building. With the help of JWT for authenticating, you can quickly build a lightweight, turbo-fast, and highly efficient REST API for user management. This guide will cover your creation journey in the process of a Flask REST API for registration and login and authentication of users. From installing necessary tools to the final testing, this guide will describe a thorough way with examples of code and practice. Get on board and let’s launch!

Step 1: Setting Up Your Environment

Requirements:

  • Python (version 3.6 or later)
  • pip (Python package installer)

First things first, ensure you have Python and pip installed on your system. You can check this by running python --version and pip --version in your terminal. If you don’t have Python installed, head over to the Python official website to download and install it.

Create a Virtual Environment:

Navigate to your project directory in the terminal and run the following command to create a virtual environment named venv:

python -m venv venv

Activate the virtual environment with:

  • On Windows: venv\Scripts\activate
  • On MacOS/Linux: source venv/bin/activate

Install Flask and PyJWT:

With your virtual environment activated, install Flask and PyJWT (a Python library to work with JWT):

pip install Flask PyJWT

Step 2: Project File Structure

Organizing your project files effectively from the start makes development smoother. Here’s a simple structure to follow:

/flask_jwt_auth
    /app
        __init__.py
        models.py
        routes.py
    /instance
        config.py
    run.py
  • __init__.py: Initializes your Flask application and brings together other components.
  • models.py: Defines data models, in this case, a User model.
  • routes.py: Contains the endpoints for user signup, login, and a protected route.
  • config.py: Stores configuration variables.
  • run.py: Starts the Flask application.

Step 3: Initialize the Flask Application

run.py:

from app import create_app

app = create_app()

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

app/__init__.py:

Create a function create_app that initializes your Flask app and registers blueprints (if you’re using them).

from flask import Flask
from .routes import main

def create_app():
    app = Flask(__name__)
    app.config.from_pyfile('instance/config.py')
    
    app.register_blueprint(main)
    
    return app

Step 4: User Model and SQLAlchemy

Install Flask-SQLAlchemy:

pip install Flask-SQLAlchemy

app/models.py:

Define a User model with SQLAlchemy to handle user data.

from flask_sqlalchemy import SQLAlchemy

db = SQLAlchemy()

class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(50), unique=True, nullable=False)
    password = db.Column(db.String(80), nullable=False)

Step 5: Configuration

instance/config.py:

Set your secret key and database URI.

SECRET_KEY = 'your_secret_key'
SQLALCHEMY_DATABASE_URI = 'sqlite:///yourdatabase.db'

Step 6: Routes and JWT

app/routes.py:

Implement the signup and login routes, utilizing JWT for authentication.

from flask import Blueprint, request, jsonify, current_app
from werkzeug.security import generate_password_hash, check_password_hash
import jwt
import datetime
from .models import User, db

main = Blueprint('main', __name__)

@main.route('/signup', methods=['POST'])
def signup():
    # User signup logic goes here

@main.route('/login', methods=['POST'])
def login():
    # User login logic goes here

@main.route('/protected', methods=['GET'])
def protected():
    # Protected route logic goes here

In the /signup route, you’ll want to hash the password before saving the user. For /login, you’ll validate the user’s credentials and return a JWT token if successful. The /protected route will require a valid JWT token to access.

Step 7: Handling User Signup

Adding a User:

In the /signup endpoint, extract user details from request.json, hash the password, and add the new user to the database.

@main.route('/signup', methods=['POST'])
def signup():
    data = request.json
    
    new_user = User(username=data['username'], password=generate_password_hash(data['password'], method='sha256'))
    
    db.session.add(new_user)
    db.session.commit()
    
    return jsonify({'message': 'Registered successfully!'}), 201

Step 8: User Login and Returning a JWT Token

Validating Credentials:

In the /login route, verify the username and password. If they’re correct, return a JWT token.

@main.route('/login', methods=['POST'])
def login():
    auth = request.json

    user = User.query.filter_by(username=auth['username']).first()
    
    if user and check_password_hash(user.password, auth['password']):
        token = jwt.encode({'id': user.id, 'exp': datetime.datetime.utcnow() + datetime.timedelta(hours=24)}, current_app.config['SECRET_KEY'])
        return jsonify({'token': token.decode('UTF-8')})
    
    return jsonify({'message': 'Could not verify'}), 401

Step 9: Protecting Routes

Verifying JWT Tokens:

Use the JWT token to protect routes. You can create a decorator or a function to validate tokens.

@main.route('/protected', methods=['GET'])
def protected():
    token = request.args.get('token')
    
    if not token:
        return jsonify({'message': 'Token is missing!'}), 403
    
    try:
        data = jwt.decode(token, current_app.config['SECRET_KEY'])
        current_user = User.query.filter_by(id=data['id']).first()
    except:
        return jsonify({'message': 'Token is invalid!'}), 403
    
    return jsonify({'message': 'This is only available for people with valid tokens.'})

Step 10: Running Your API

Finally, ensure your database is initialized by adding at the end of your models.py:

@app.before_first_request
def create_tables():
    db.create_all()

Now, run your Flask application with python run.py and test your API endpoints using tools like Postman or cURL.

Conclusion

Congratulations! You’ve just set up a Flask REST API with user signup and login functionality, using JWT for secure authentication. This setup provides a solid foundation for building robust web applications with Flask. Remember, the world of web development is always evolving, so keep experimenting and learning.

Feel free to tweak and expand upon this example to suit your project’s needs. Flask is incredibly flexible, allowing you to add more features like password reset, email verification, and much more. Happy coding!

Leave a Comment

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *