SoFunction
Updated on 2025-04-20

Detailed Guide to Calling Java Data Interface to Implement CRUD Operations

introduction

In modern software architectures, data interaction between systems is becoming increasingly important. As two popular programming languages, Python and Java often need to implement cross-language data interaction in enterprise-level applications. This report will introduce in detail how to call the Java data interface in the Django Python project, and pay special attention to the implementation of the addition, deletion, modification and query (CRUD) operation. Through this article, readers will learn about best practices, implementation methods, and some advanced features of interface definition.

Interface definition specification

Interface design principles

When designing Python projects to interact with Java data interfaces, the following principles need to be followed:

  • Consistency: Ensure that all interfaces follow the same naming conventions and parameter passing rules
  • Impotence: For query-class interfaces, they should be designed as idempotent operations to ensure that repeated calls do not have side effects.
  • Parameterization: Design reasonable parameters for the interface to make the interface flexible and reusable
  • Error handling: Define a unified error handling mechanism to facilitate the client to understand and handle exceptions

Basic interface structure

A complete interface definition should contain the following elements:

  • URI path: interface access path, usually designed in RESTful style
  • HTTP methods: GET, POST, PUT, DELETE and other HTTP methods
  • Request parameters: query parameters, path parameters or request body parameters
  • Response format: usually in JSON format, including status code, data and error information

Interface definition example

1. Query all provinces

{
  "interface": {
    "name": "Query all provinces",
    "method": "GET",
    "path": "/api/provinces/",
    "parameters": [],
    "response": {
      "schema": {
        "type": "object",
        "properties": {
          "data": {
            "type": "array",
            "items": {"type": "string"}
          },
          "timestamp": {"type": "string", "format": "date-time"}
        }
      },
      "example": {
        "data": ["Guangdong Province", "Jiangsu Province", "Zhejiang Province", ...],
        "timestamp": "2025-04-17T18:27:30Z"
      }
    }
  }
}

2. Query the Notice list by condition

{
  "interface": {
    "name": "Query Notice List by Condition",
    "method": "GET",
    "path": "/api/notices/",
    "parameters": [
      {"name": "province", "type": "string", "description": "Province Name", "in": "query"},
      {"name": "publishdate", "type": "string", "description": "Published time, format: YYYY-MM-DD", "in": "query"},
      {"name": "doctype", "type": "string", "description": "Document Type", "in": "query"}
    ],
    "response": {
      "schema": {
        "type": "object",
        "properties": {
          "data": {
            "type": "array",
            "items": {
              "type": "object",
              "properties": {
                "id": {"type": "integer"},
                "title": {"type": "string"},
                "province": {"type": "string"},
                "publishdate": {"type": "string", "format": "date"},
                "doctype": {"type": "string"}
              }
            }
          },
          "timestamp": {"type": "string", "format": "date-time"}
        }
      },
      "example": {
        "data": [{"id": 123, "title": "Announcement of Tender for a Project", "province": "Guangdong Province", "publishdate": "2025-04-01", "doctype": "Tender Announcement"}],
        "timestamp": "2025-04-17T18:27:30Z"
      }
    }
  }
}

3. Combination search

{
  "interface": {
    "name": "Combination Search",
    "method": "POST",
    "path": "/api/combined-search/",
    "parameters": [],
    "request": {
      "schema": {
        "type": "object",
        "properties": {
          "filters": {"type": "object", "properties": {"province": {"type": "string"}}, "description": "Filter Conditions"},
          "options": {"type": "object", "properties": {"daysbefore": {"type": "integer"}}, "description": "Option Parameters"}
        }
      },
      "example": {"filters": {"province": "Zhejiang Province"}, "options": {"daysbefore": 7}}
    },
    "response": {
      "schema": {
        "type": "object",
        "properties": {"notices": {"type": "array", "items": {"$ref": "#/components/schemas/Notice"}} // Assume that Notice is a well-defined pattern      },
      "example": {"notices": [{"id": 123, "title": "Announcement of Tender for a Project", "province": "Zhejiang Province", "publishdate": "2025-04-11", "doctype": "Tender Announcement"}]}
    }
  }
}

Interface implementation

Django view implementation

According to the above interface definition, the following is an implementation example of Django view:

# 
from  import require_http_methods
from  import JsonResponse
import json
@require_http_methods(["GET"])
def provinces_list(request):
    # Call Java interface to get the province list    provinces = ["Guangdong Province", "Jiangsu Province", "Zhejiang Province"]  # Simulate data    timestamp = "2025-04-17T18:27:30Z"
    return JsonResponse({"data": provinces, "timestamp": timestamp})
@require_http_methods(["GET"])
def notices_list(request):
    province = ("province")
    publishdate = ("publishdate")
    doctype = ("doctype")
    
    # Call Java interface to get the Notice list    notices = [{"id": 123, "title": "Announcement of Tender for a Project", "province": "Guangdong Province", "publishdate": "2025-04-01", "doctype": "Tender Announcement"}]  # Simulate data    timestamp = "2025-04-17T18:27:30Z"
    return JsonResponse({"data": notices, "timestamp": timestamp})
@require_http_methods(["POST"])
def combined_search(request):
    try:
        data = ()
        filters = ("filters", {})
        options = ("options", {})
        
        province = ("province")
        daysbefore = ("daysbefore")
        
        # Call Java interface for combined search        notices = [{"id": 123, "title": "Announcement of Tender for a Project", "province": "Zhejiang Province", "publishdate": "2025-04-11", "doctype": "Tender Announcement"}]  # Simulate data        
        return JsonResponse({"notices": notices})
    except :
        return JsonResponse({"error": "Invalid JSON format"}, status=400)

URL routing configuration

Add the following routing configuration in your Django project:

# 
from  import path
from . import views
urlpatterns = [
    path('api/provinces/', views.provinces_list, name='provinces_list'),
    path('api/notices/', views.notices_list, name='notices_list'),
    path('api/combined-search/', views.combined_search, name='combined_search'),
]

Java interface call

In actual applications, Django views need to call Java interface. The following is the sample code for calling the Java interface:

import requests
def call_java_api(url, method, params=None, data=None):
    if method == "GET":
        response = (url, params=params)
    elif method == "POST":
        response = (url, json=data)
    elif method == "PUT":
        response = (url, json=data)
    elif method == "DELETE":
        response = (url)
    else:
        raise ValueError("Unsupported HTTP method")
    
    if response.status_code == 200:
        return ()
    else:
        raise Exception(f"API call failed: {response.status_code} - {}")

Testing and performance

Unit Testing

Here is an example unit test for the above interface:

# 
from  import TestCase, Client
import json
class APITestCase(TestCase):
    def setUp(self):
         = Client()
    
    def test_provinces_list(self):
        response = ('/api/provinces/')
        (response.status_code, 200)
        content = ()
        ('data', content)
        ('timestamp', content)
    
    def test_notices_list(self):
        response = ('/api/notices/?province=Guangdong Province&publishdate=2025-04-01&doctype=Tender Announcement')
        (response.status_code, 200)
        content = ()
        ('data', content)
        ('timestamp', content)
    
    def test_combined_search(self):
        data = {
            "filters": {"province": "Zhejiang Province"},
            "options": {"daysbefore": 7}
        }
        response = ('/api/combined-search/', (data), content_type='application/json')
        (response.status_code, 200)
        content = ()
        ('notices', content)

Performance pressure measurement

Here are the commands for performance pressure measurement using Vegeta:

# Use Vegeta for stress testingvegeta attack -body testdata/ -rate 100/s -duration 30s | vegeta report

Monitoring indicators

The following is the Prometheus monitoring configuration:

# prometheus/
- job_name: 'djangoapi'
  metrics_path: '/metrics'
  static_configs:
    - targets: ['django:8000']

Document generation

To generate interactive documents, the drf-spectacular library can be used. Here is a configuration example:

# 
INSTALLED_APPS = [
    ...
    'drf_spectacular',
    ...
]
SPECTACULAR_SETTINGS = {
    'TITLE': 'Django API',
    'DESCRIPTION': 'Django API documentation',
    'VERSION': '1.0.0',
    'SERVE_INCLUDE_SCHEMA': False,
    'SWAGGER_UI_DIST': 'SIDECAR',
    'SWAGGER_UI_FAVICON_HREF': 'SIDECAR',
    'REDOC_DIST': 'SIDECAR',
}

Then, use the @extend_schema annotation in the view:

# 
from drf_spectacular.utils import extend_schema
@extend_schema(
    request=None,
    responses={
        200: {
            'type': 'object',
            'properties': {
                'data': {
                    'type': 'array',
                    'items': {'type': 'string'}
                },
                'timestamp': {'type': 'string', 'format': 'date-time'}
            }
        }
    }
)
def provinces_list(request):
    # Interface implementation    pass

Version control

In order to implement version control of the interface, you can add the version number to the URL:

# 
from  import path
from . import views
urlpatterns = [
    path('api/v1/provinces/', views.provinces_list, name='provinces_list'),
    path('api/v1/notices/', views.notices_list, name='notices_list'),
    path('api/v1/combined-search/', views.combined_search, name='combined_search'),
]

Safety considerations

To improve the security of the interface, the following measures can be taken:

  • Authentication and authorization: Use JWT or OAuth2 and other authentication mechanisms
  • Input Verification: Verify user input to prevent SQL injection and XSS attacks
  • Rate limit: Use Django's ratelimit library to limit request frequency
  • HTTPS: Ensure that the interface is accessed through HTTPS
  • CORS configuration: Configure cross-domain resource sharing (CORS)

This is the article about this detailed guide on Python calling Java data interface to implement CRUD operations. For more related Python CRUD operations, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!