DEV Community

Cover image for How to Create Rest API with Python: A Step-by-Step Guide
Hardik Mervana
Hardik Mervana

Posted on

How to Create Rest API with Python: A Step-by-Step Guide

A REST API allows various systems to exchange data over HTTP in a straightforward way. Python is a popular programming language for developing REST APIs thanks to its simplicity, flexibility, and wide support. This guide will walk you through the step-by-step process of building a simple REST API using Python.

Overview of REST API Architecture

REST (Representational State Transfer) is an architectural style for developing web services. A REST API breaks down a transaction to create a series of small modules, each handling a discrete action. This allows different systems to communicate with each other effectively.

Image description

The key principles of REST API architecture are:

  • Client-Server: There is a separation between the client requesting the information and the server supplying it.
  • Stateless: No client information is stored on the server between requests. Session state is held on the client side.
  • Cacheable: API responses indicate if they can be cached to improve performance.
  • Uniform Interface: Resources are identified and accessed using uniform resource identifiers (URIs).
  • Layered System: Clients cannot tell if they are connected directly to the end server or middleware.

By following these constraints, REST systems aim to be fast, scalable, and easy to maintain.

A Step-by-Step Guide to Build a REST API in Python

We will build a simple REST API in Python that can perform CRUD operations on a database to demonstrate core concepts. The steps involved are:

1. Set Up the Project

First, we need to set up a new Python project. Make sure Python 3 is installed then follow these steps:

  • Create a new project folder called python-rest-api.
  • Open a terminal in the project folder and initialize a new virtual environment:
python3 -m venv env
Enter fullscreen mode Exit fullscreen mode
  • Activate the virtual environment:
source env/bin/activate
Enter fullscreen mode Exit fullscreen mode
  • Install Flask and Flask-SQLAlchemy:
pip install flask flask-sqlalchemy
Enter fullscreen mode Exit fullscreen mode

Flask provides the core framework while Flask-SQLAlchemy makes it easier to interact with databases.

2. Define Models and Database

Next, we need to set up the database models and SQLAlchemy to manage database connections and queries.

Inside the python-rest-api folder, create a new file called models.py:

from flask_sqlalchemy import SQLAlchemy

db = SQLAlchemy()

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

    def __repr__(self):
        return '<User %r>' % self.username

Enter fullscreen mode Exit fullscreen mode

This defines a simple User model with id, username, and email fields.

Now in app.py, we can initialize SQLAlchemy:

from flask import Flask
from models import db

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///database.db'
db.init_app(app)
Enter fullscreen mode Exit fullscreen mode

This will connect to a SQLite database file called database.db.

3. Define Routes and Views

With the models and database setup, we can now define the routes and views for the API.

In app.py, add the following view functions:

@app.route('/users', methods=['GET'])
def get_users():
    users = User.query.all()
    return  {'users': [user.serialize() for user in users]}

@app.route('/users/<int:id>', methods=['GET'])
def get_user(id):
    user = User.query.filter_by(id=id).first()
    return user.serialize()

@app.route('/users', methods=['POST'])
def create_user():
    # Create user logic
    pass

@app.route('/users/<int:id>', methods=['PUT'])
def update_user(id):
    # Update user logic
    pass  

@app.route('/users/<int:id>', methods=['DELETE']) 
def delete_user(id):
    # Delete user logic
    pass
Enter fullscreen mode Exit fullscreen mode

This implements GET, POST, PUT, and DELETE methods for /users and /users/:id routes to perform CRUD operations.

4. Add API Request and Response Handling

With the routes defined, we can fill in the logic for handling requests and returning responses:

from flask import request, jsonify

# GET /users
# Return list of users

@app.route('/users', methods=['GET'])
def get_users():
    users = User.query.all()
    return jsonify([user.serialize() for user in users])

# GET /users/:id
# Return specific user based on id

@app.route('/users/<int:id>', methods=['GET']) 
def get_user(id):
    user = User.query.filter_by(id=id).first()
    return jsonify(user.serialize())

# POST /users
# Create new user

@app.route('/users', methods=['POST'])
def create_user():
    data = request.get_json()
    username = data['username']
    email = data['email']

    user = User(username=username, email=email)
    db.session.add(user)
    db.session.commit()

    return jsonify(user.serialize())

# PUT /users/:id
# Update user based on id

@app.route('/users/<int:id>', methods=['PUT'])
def update_user(id):
    user = User.query.filter_by(id=id).first()

    data = request.get_json()
    user.username = data['username']
    user.email = data['email']

    db.session.commit()

    return jsonify(user.serialize())

# DELETE /users/:id
# Delete user

@app.route('/users/<int:id>', methods=['DELETE'])
def delete_user(id):
    user = User.query.filter_by(id=id).first()
    db.session.delete(user)
    db.session.commit()

    return jsonify({'message': 'User deleted'})
Enter fullscreen mode Exit fullscreen mode

This implements the request handling and API responses for each CRUD operation.

5. Run the Development Server

Our simple REST API with Python is now ready. We can test it by running the Flask development server:

python app.py
Enter fullscreen mode Exit fullscreen mode

This will start the server on localhost port 5000.

We can send API requests and see the JSON responses:

# GET /users
curl http://localhost:5000/users

# POST /users 
curl -X POST -H "Content-Type: application/json" -d '{"username":"testuser","email":"test@example.com"}' http://localhost:5000/users

# GET /users/:id
curl http://localhost:5000/users/1  

# PUT /users/:id
curl -X PUT -H "Content-Type: application/json" -d '{"username":"updateduser","email":"updated@email.com"}' http://localhost:5000/users/1

# DELETE /users/:id
curl -X DELETE http://localhost:5000/users/1
Enter fullscreen mode Exit fullscreen mode

This confirms our REST API works correctly!

6. Add Authentication, Testing, etc

For a production REST API, there are some additional important steps:

  • Add authentication to secure access to the API. JSON Web Tokens (JWT) are a popular choice.
  • Validate incoming data to protect against incorrect or malicious requests.
  • Write unit and integration tests for the API endpoints. Pytest is a good option for Python testing.
  • Containerize the API using Docker to simplify deployment.
  • Set up logging to track requests and errors.
  • Document the API using OpenAPI (formerly Swagger) specification.

These steps are outside the initial scope but turn a simple API into a robust, production-ready system.

Frequently Asked Questions

What is the benefit of using Flask for REST APIs?

Flask is a lightweight Python web framework that makes it easy to create REST APIs. It has minimal boilerplate code, flexible routing, and strong ecosystem support. This simplicity and flexibility makes Flask a popular choice for developing REST APIs in Python.

How do I handle data persistence in a Flask REST API?

Flask-SQLAlchemy provides ORM integration for managing data persistence with Flask. It handles interactions with SQL databases and abstracts away raw SQL queries. Other options like Flask-MongoEngine allow using NoSQL databases like MongoDB.

How do I implement authentication and security in a Flask REST API?

Use Flask extensions like Flask-JWT or Flask-HTTPAuth to implement token or HTTP authentication workflows for securing REST APIs. Enable HTTPS encryption to protect data in transit. Use middleware to handle things like rate limiting and threat protection.

What is the best way to document a Flask REST API?

Use OpenAPI (formerly Swagger) to create a YAML or JSON spec that documents your REST API endpoints. This provides interactive documentation and can generate client code stubs in many languages automatically. Flask extensions like flasgger can integrate OpenAPI into your Flask app.

How do I install Python to build a REST API?

To install Python on Windows, macOS, and Linux systems, follow these steps:

  • Windows: Download the Python installer from python.org and run it. This will install Python, pip, and add Python to your PATH.
  • macOS: Install Python using Homebrew with brew install python3 or by downloading the installer from python.org.
  • Linux: Python is generally included already in Linux distributions. You may need to install the python3 and pip3 packages from your package manager.

Make sure you install Python 3 (3.6 or higher). After installing Python, you can verify it is installed and check the version with python3 --version on the command line. This will ensure you have Python ready to start building your REST APIs.

How should I test my Flask REST API?

Write unit tests for the endpoints using the Flask test client and mock data. Use pytest or unittest for tests. Also do integration/functional testing against a live database and server to validate the full API workflow. Postman and pytest can help with endpoint testing.

Top comments (0)