How to Use the API – User Registration (/register)

This endpoint allows clients to create a new user account. Registered users can then obtain JWT tokens via /auth to access protected resources. The registration process ensures unique usernames and enforces required fields.

POST /register

Use this endpoint to register a new user by supplying a JSON payload with username and password.

Request Body

Below are the fields parsed and validated by the shared RequestParser in UserRegister:

Field Type Required Description
username string Unique user identifier
password string Secret for JWT authentication

Example Request

curl -X POST http://localhost:5000/register \
  -H "Content-Type: application/json" \
  -d '{
    "username": "johndoe",
    "password": "secret123"
}'

Responses

  • 201 Created

🎉

  • 400 Bad Request
  • Username already exists
  • Missing required fields (parser enforces both fields)
{
  "message": "A user with that username already exists"
}

Register a New User [POST]

{
    "title": "User Registration",
    "description": "Create a new user account for JWT-based access.",
    "method": "POST",
    "baseUrl": "http://localhost:5000",
    "endpoint": "/register",
    "headers": [
        {
            "key": "Content-Type",
            "value": "application/json",
            "required": true
        }
    ],
    "queryParams": [],
    "pathParams": [],
    "bodyType": "json",
    "requestBody": "{\n  \"username\": \"johndoe\",\n  \"password\": \"secret123\"\n}",
    "formData": [],
    "rawBody": "",
    "responses": {
        "201": {
            "description": "User created successfully.",
            "body": "{ \"message\": \"User created successfully.\" }"
        },
        "400": {
            "description": "Username exists or missing fields.",
            "body": "{ \"message\": \"A user with that username already exists\" }"
        }
    }
}

Implementation Details

UserRegister Resource

The UserRegister class handles registration logic:

from flask_restful import Resource, reqparse
from models.user import UserModel

class UserRegister(Resource):
    parser = reqparse.RequestParser()
    parser.add_argument('username',
                        type=str,
                        required=True,
                        help="This field cannot be blank.")
    parser.add_argument('password',
                        type=str,
                        required=True,
                        help="This field cannot be blank.")

    def post(self):
        data = UserRegister.parser.parse_args()
        if UserModel.find_by_username(data['username']):
            return {"message": "A user with that username already exists"}, 400

        user = UserModel(data['username'], data['password'])
        user.save_to_db()
        return {"message": "User created successfully."}, 201

This parser enforces presence of both fields and returns custom help messages on failure.

UserModel

The UserModel represents the users table and provides lookup and persistence methods:

from db import db

class UserModel(db.Model):
    __tablename__ = 'users'

    id       = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(80))
    password = db.Column(db.String(80))

    def __init__(self, username, password):
        self.username = username
        self.password = password

    @classmethod
    def find_by_username(cls, username):
        return cls.query.filter_by(username=username).first()

    def save_to_db(self):
        db.session.add(self)
        db.session.commit()

This model ensures unique username checks and basic persistence.

Registration in app.py

Register the resource with Flask-RESTful in app.py:

from resources.user import UserRegister

api.add_resource(UserRegister, '/register')

This maps POST /register to the UserRegister.post method.


Best Practices

{
    "title": "Secure Passwords",
    "content": "Store hashed passwords instead of plain text for enhanced security."
}
  • Consider integrating password hashing (e.g., via Werkzeug’s generate_password_hash) before saving.
  • Validate password strength on the client or server side.

This completes the user registration documentation for the Flask REST API.