Python Backend Development Tutorial – Build Your First API Step by Step
The best way to learn backend development is to build something real. Reading about frameworks, databases, and APIs is useful, but the concepts only truly click when you have written the code yourself, encountered the errors, and watched your application come to life. This tutorial is designed to take you through that process from start to finish.
Over the course of this guide, you will build a task management API from scratch. You will set up a Python project, create a web application with Flask, connect it to a database, implement user registration and login, add authentication, write tests, and deploy the application. By the end, you will have a working API and, more importantly, a practical understanding of how the pieces of a Python backend fit together.
The tutorial uses Flask because it is minimal and lets you see each component clearly. Once you understand these fundamentals, moving to Django or FastAPI becomes much easier. Every concept here transfers directly.
At V3design Nigeria, we build production APIs every day. This tutorial is structured the way we would teach a new developer joining our team.
For more insights, check out our articles on Learn Coding in Benin City, Tech Academy in Benin City, and Software Development Training in Benin City.
What You Will Build
Before writing any code, it helps to know where you are going. By the end of this tutorial, you will have a task management API with the following features:
- User Registration: Create a new account with an email and password.
- User Login: Authenticate and receive a token.
- Create Tasks: Add tasks associated with the logged-in user.
- List Tasks: Retrieve all tasks belonging to the user.
- Update Tasks: Modify the title or completion status of a task.
- Delete Tasks: Remove a task.
- Protected Routes: Ensure only the authenticated user can access their own tasks.
- Tests: Automated tests covering the main endpoints.
- Deployment: A running application accessible over the internet.
This is a small but complete application. It includes every category of concern you will encounter in a real backend: routing, validation, persistence, authentication, authorization, testing, and deployment.
Prerequisites and Setup
Before starting, make sure you have the following in place.
- Python installed: Python 3.10 or later is recommended. You can check your version by running
python --versionin your terminal. - A code editor: Visual Studio Code, PyCharm, or any editor you are comfortable with.
- Basic Python knowledge: You should understand variables, functions, classes, and how to run a Python script.
- Command line familiarity: You should be able to navigate directories and run commands.
- Git installed: Optional for the tutorial, but strongly recommended for tracking your work.
Once you have these, create a new directory for the project and navigate into it.
$ cd task-api
Step 1 – Create a Virtual Environment
Every Python project should have its own virtual environment. This isolates the project's dependencies from other projects on your machine, preventing version conflicts.
Activate the virtual environment. On macOS and Linux:
On Windows:
You should see the environment name in your terminal prompt, indicating that it is active. Now install the packages you will need.
$ pip install flask-jwt-extended python-dotenv
$ pip install pytest
Here is what each package does. Flask is the web framework. Flask-SQLAlchemy integrates the SQLAlchemy ORM. Flask-Migrate handles database migrations. Flask-JWT-Extended provides JSON Web Token authentication. python-dotenv loads configuration from environment files. pytest is the testing framework.
Save your dependencies so they can be reinstalled later.
Step 2 – Set Up the Project Structure
A clean project structure makes the code easier to navigate and maintain. Create the following files and directories.
├── app/
│ ├── __init__.py
│ ├── models.py
│ ├── routes.py
│ └── config.py
├── tests/
│ └── test_tasks.py
├── .env
├── run.py
└── requirements.txt
This structure separates configuration, models, routes, and tests. As the application grows, you can add more modules without creating a mess.
Step 3 – Configure the Application
Configuration should never be hard-coded. Use environment variables so that secrets and settings can differ between development and production. Create a file named .env in the project root.
JWT_SECRET_KEY=change-this-too
DATABASE_URL=sqlite:///tasks.db
Now create app/config.py to load these values.
from dotenv import load_dotenv
load_dotenv()
class Config:
SECRET_KEY = os.getenv('SECRET_KEY')
JWT_SECRET_KEY = os.getenv('JWT_SECRET_KEY')
SQLALCHEMY_DATABASE_URI = os.getenv('DATABASE_URL')
SQLALCHEMY_TRACK_MODIFICATIONS = False
Notice that the database URL points to SQLite for development. SQLite requires no separate server, which keeps the tutorial simple. In production, you would replace this with a PostgreSQL connection string.
Step 4 – Create the Application Factory
Instead of creating the Flask application at the module level, use an application factory. This pattern makes testing easier because you can create multiple application instances with different configurations.
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
from flask_jwt_extended import JWTManager
from .config import Config
db = SQLAlchemy()
migrate = Migrate()
jwt = JWTManager()
def create_app(config_class=Config):
app = Flask(__name__)
app.config.from_object(config_class)
db.init_app(app)
migrate.init_app(app, db)
jwt.init_app(app)
from .routes import api
app.register_blueprint(api, url_prefix='/api')
return app
The db, migrate, and jwt objects are created outside the factory and initialized inside it. This is a common pattern that allows models and routes to import these objects without circular import problems.
Step 5 – Define the Database Models
Models define the structure of your data. You will create two models: a User and a Task. Each task belongs to a user, establishing a relationship between the two.
from datetime import datetime
from werkzeug.security import generate_password_hash, check_password_hash
from . import db
class User(db.Model):
__tablename__ = 'users'
id = db.Column(db.Integer, primary_key=True)
email = db.Column(db.String(120), unique=True, nullable=False)
password_hash = db.Column(db.String(255), nullable=False)
created_at = db.Column(db.DateTime, default=datetime.utcnow)
tasks = db.relationship('Task', backref='owner', lazy=True, cascade='all, delete-orphan')
def set_password(self, password):
self.password_hash = generate_password_hash(password)
def check_password(self, password):
return check_password_hash(self.password_hash, password)
class Task(db.Model):
__tablename__ = 'tasks'
id = db.Column(db.Integer, primary_key=True)
title = db.Column(db.String(200), nullable=False)
done = db.Column(db.Boolean, default=False)
user_id = db.Column(db.Integer, db.ForeignKey('users.id'), nullable=False)
created_at = db.Column(db.DateTime, default=datetime.utcnow)
Several important decisions are embedded in these models. Passwords are stored as hashes, never as plain text. The relationship between users and tasks uses a foreign key, and the cascade ensures that deleting a user also deletes their tasks. The user_id column is what allows you to enforce that users can only access their own tasks.
Step 6 – Build the API Routes
Routes define the endpoints of your API. You will create endpoints for registration, login, and CRUD operations on tasks. Create app/routes.py.
from flask import Blueprint, request, jsonify
from flask_jwt_extended import create_access_token, jwt_required, get_jwt_identity
from . import db
from .models import User, Task
api = Blueprint('api', __name__)
@api.route('/register', methods=['POST'])
def register():
data = request.get_json()
email = data.get('email')
password = data.get('password')
if not email or not password:
return jsonify({'error': 'Email and password required'}), 400
if User.query.filter_by(email=email).first():
return jsonify({'error': 'Email already registered'}), 409
user = User(email=email)
user.set_password(password)
db.session.add(user)
db.session.commit()
return jsonify({'message': 'User created'}), 201
@api.route('/login', methods=['POST'])
def login():
data = request.get_json()
user = User.query.filter_by(email=data.get('email')).first()
if not user or not user.check_password(data.get('password', '')):
return jsonify({'error': 'Invalid credentials'}), 401
token = create_access_token(identity=str(user.id))
return jsonify({'access_token': token}), 200
The registration endpoint validates input, checks for duplicate emails, hashes the password, and saves the user. The login endpoint verifies credentials and issues a JWT containing the user's identifier.
Now add the task endpoints. These all require authentication, enforced with the @jwt_required() decorator. The current user's identity is retrieved with get_jwt_identity(), and every query is filtered by that user ID to prevent one user from accessing another's data.
@jwt_required()
def list_tasks():
user_id = int(get_jwt_identity())
tasks = Task.query.filter_by(user_id=user_id).all()
return jsonify([
{'id': t.id, 'title': t.title, 'done': t.done}
for t in tasks
]), 200
@api.route('/tasks', methods=['POST'])
@jwt_required()
def create_task():
user_id = int(get_jwt_identity())
data = request.get_json()
title = data.get('title')
if not title:
return jsonify({'error': 'Title required'}), 400
task = Task(title=title, user_id=user_id)
db.session.add(task)
db.session.commit()
return jsonify({
'id': task.id,
'title': task.title,
'done': task.done
}), 201
@api.route('/tasks/<int:task_id>', methods=['PUT'])
@jwt_required()
def update_task(task_id):
user_id = int(get_jwt_identity())
task = Task.query.filter_by(id=task_id, user_id=user_id).first()
if not task:
return jsonify({'error': 'Task not found'}), 404
data = request.get_json()
task.title = data.get('title', task.title)
task.done = data.get('done', task.done)
db.session.commit()
return jsonify({'message': 'Task updated'}), 200
@api.route('/tasks/<int:task_id>', methods=['DELETE'])
@jwt_required()
def delete_task(task_id):
user_id = int(get_jwt_identity())
task = Task.query.filter_by(id=task_id, user_id=user_id).first()
if not task:
return jsonify({'error': 'Task not found'}), 404
db.session.delete(task)
db.session.commit()
return jsonify({'message': 'Task deleted'}), 200
Step 7 – Create the Entry Point
Create run.py in the project root. This is the file you will execute to start the server.
from app import create_app
app = create_app()
if __name__ == '__main__':
app.run(debug=True)
Step 8 – Initialize the Database
Flask-Migrate manages database schema changes. Initialize it once, then generate and apply a migration to create the tables.
$ flask --app run db migrate -m "initial tables"
$ flask --app run db upgrade
You should now see a migrations folder and a tasks.db file. The database tables have been created. Now start the server.
Your API is now running at http://localhost:5000. Test the registration endpoint using curl or Postman.
-H "Content-Type: application/json" \
-d '{"email":"[email protected]","password":"secret123"}'
If everything is working, you will receive a message confirming the user was created. Try logging in, then use the returned token to access the task endpoints.
Step 9 – Write Automated Tests
Tests protect your application from regressions. They also force you to think about edge cases. Create tests/test_tasks.py.
import pytest
from app import create_app, db
from app.config import Config
class TestConfig(Config):
TESTING = True
SQLALCHEMY_DATABASE_URI = 'sqlite:///:memory:'
@pytest.fixture
def client():
app = create_app(TestConfig)
with app.app_context():
db.create_all()
yield app.test_client()
db.drop_all()
def register_and_login(client):
client.post('/api/register', json={
'email': '[email protected]',
'password': 'password123'
})
response = client.post('/api/login', json={
'email': '[email protected]',
'password': 'password123'
})
return response.get_json()['access_token']
def test_register_and_login(client):
token = register_and_login(client)
assert token is not None
def test_create_and_list_tasks(client):
token = register_and_login(client)
headers = {'Authorization': f'Bearer {token}'}
client.post('/api/tasks', json={'title': 'Write tests'}, headers=headers)
response = client.get('/api/tasks', headers=headers)
tasks = response.get_json()
assert len(tasks) == 1
assert tasks[0]['title'] == 'Write tests'
def test_tasks_require_auth(client):
response = client.get('/api/tasks')
assert response.status_code == 401
Run the tests with pytest.
The tests use an in-memory database, so they do not touch your development data. They verify that registration and login work, that tasks can be created and listed, and that protected routes reject unauthenticated requests.
Step 10 – Deploy the Application
Running the Flask development server is fine for local work, but production requires a proper application server and a reverse proxy. The standard setup is Gunicorn behind Nginx.
First, install Gunicorn and add it to your requirements.
$ pip freeze > requirements.txt
Create a file named wsgi.py in the project root.
from app import create_app
app = create_app()
You can now run the application with Gunicorn.
In a real deployment, you would run this behind Nginx, which handles TLS termination and serves static files. You would also replace SQLite with PostgreSQL, store secrets in a secrets manager rather than a .env file, and set up process supervision so the application restarts automatically if it crashes.
What to Learn Next
You now have a working API. Here are the natural next steps to deepen your skills.
- Add pagination and filtering: Real APIs rarely return every record at once. Add query parameters for pagination, search, and sorting.
- Add refresh tokens: Access tokens expire. Implement refresh tokens so users are not logged out unexpectedly.
- Add rate limiting: Protect authentication endpoints from brute-force attempts.
- Add background tasks: Move slow operations such as sending emails into a task queue with Celery.
- Add caching: Introduce Redis to cache frequently requested data.
- Add structured logging: Replace print statements with structured logs that can be searched and alerted on.
- Write API documentation: Generate OpenAPI documentation so consumers know how to use your API.
- Learn a second framework: Try rebuilding the same API in Django or FastAPI to understand the trade-offs.
- Containerize the application: Write a Dockerfile so the application runs consistently everywhere.
- Set up continuous integration: Run your tests automatically on every push.
What Learners Say About This Approach
"I had read about Flask and SQLAlchemy many times, but building the task API is what made it click. Connecting the models to the routes and seeing the data persist was the moment it became real for me."
"The section on authentication was the most valuable part. I had always wondered how tokens worked. Writing the login endpoint and then protecting routes with the token made the whole concept concrete."
"Writing the tests forced me to think about what could go wrong. The test that checks unauthenticated requests are rejected caught a bug I would have shipped otherwise. I now write tests first for anything important."
Frequently Asked Questions
What will I build in this Python backend tutorial?
You will build a task management API with user registration, login, and CRUD operations for tasks. The tutorial covers project setup, Flask, SQLAlchemy, database migrations, authentication with JWT, testing, and deployment.
Do I need prior experience to follow this tutorial?
You should be comfortable with basic Python syntax such as variables, functions, and classes. No prior web development experience is required, but familiarity with the command line and Git will help.
Which framework does this tutorial use?
This tutorial uses Flask because it is minimal and lets you see how each component fits together. The concepts transfer directly to Django and FastAPI.
How long does it take to complete this tutorial?
Working through the tutorial carefully, including typing the code and testing it, typically takes several hours spread over a few sessions. Take your time and make sure each step works before moving on.
Why use SQLite instead of PostgreSQL for the tutorial?
SQLite requires no separate server, which keeps the tutorial focused on backend concepts rather than database setup. The code is written so that switching to PostgreSQL later requires only a change to the database URL.
Is the code in this tutorial production-ready?
It is a solid foundation, but production systems require additional work: refresh tokens, rate limiting, structured logging, monitoring, a secrets manager, and a proper database. The "What to Learn Next" section outlines these steps.
You Have Built a Backend
You started with an empty directory and ended with a working API that handles registration, authentication, and task management, complete with tests and a deployment path. More importantly, you have worked through the layers that make up every Python backend: routing, validation, persistence, authentication, testing, and serving.
The next step is to keep building. Extend this API, break it, fix it, and add features until it becomes something you are proud to show. The confidence that comes from building real things is what separates developers who make progress from those who stay stuck in tutorials.
At V3design Nigeria, we mentor developers through exactly this kind of practical work. If you have questions or want feedback on your project, we are happy to help.
Explore More Resources
Software Development Training in Benin City
Web Development Classes in Benin City
Holiday Coding Camp in Benin City
Summer Tech Camp in Benin City
Coding Academy for Children in Benin City
Tech Academy Near Me in Benin City
Tech Training Institute in Benin City
Learn Software Engineering in Benin City
Website Design Company in Warri
Best Website Designer in Warri
Online Website Designer in Warri
Best Website Designer in Asaba