Extension:SemanticAPI

Category:Extensions without an imageCategory:Extensions without a compatibility policyCategory:MIT licensed extensions
MediaWiki extensions manual
SemanticAPI
Release status: stableCategory:Stable extensions
Implementation API Category:API extensions
Description MediaWiki extension that provides REST API endpoints for reading and writing Semantic MediaWiki (SMW) properties on pages.
Author(s) Bertrand Gorge (BertrandGorgetalk)
MediaWiki 1.43+Category:Extensions with manual MediaWiki version
PHP 8.0+
Licence MIT License
Download Category:Extensions in GitHub version control
https://github.com/neayi/mediawiki-extensions-SemanticAPI/blob/main/README.md
Example https://wiki.tripleperformance.fr/rest.php/semanticproperty/Maraîchage
Category:All extensionsCategory:Extensions not in ExtensionJson

A MediaWiki extension that provides REST API endpoints for reading and writing Semantic MediaWiki (SMW) properties on pages. It is similar to Extension:SemanticRESTAPI with two main differences:

  • The GET operations is much more complete, with data structure depending on the semantic type
  • PUT and DELETE operations are available

Overview

The SemanticAPI extension allows external applications to interact with Semantic MediaWiki data through a modern REST API interface. You can read existing semantic property values from pages and write new values programmatically.

Features

  • 📖 Read SMW Properties: Retrieve semantic property values from any page via GET requests
  • ✏️ Write SMW Properties: Add or update semantic property values via PUT requests
  • 🔒 Permission-based Access: Respects MediaWiki’s permission system (edit rights required for writing)
  • 📦 Multiple Input Formats: Supports both JSON and form data for PUT requests
  • 🛡️ Robust Error Handling: Comprehensive validation and meaningful error messages
  • 🌐 RESTful Design: Clean, standard REST API endpoints

Requirements

  • MediaWiki: >= 1.43
  • Semantic MediaWiki: >= 6.0
  • PHP: >= 8.0 (MediaWiki 1.43 requirement)

Installation

Prerequisites

Semantic MediaWiki must be installed first! This extension requires SMW to be installed and configured.

  1. Install Semantic MediaWiki (if not already installed):
  2. Download or clone this extension to your MediaWiki extensions directory:
cd extensions/
git clone https://github.com/neayi/mediawiki-extensions-SemanticAPI.git SemanticAPI
  1. Add to LocalSettings.php (after SMW is loaded):
// Make sure SMW is loaded first
wfLoadExtension( 'SemanticMediaWiki' );
enableSemantics( 'your-domain.org' );

// Then load SemanticAPI
wfLoadExtension( 'SemanticAPI' );
  1. Update database (if needed):
php maintenance/update.php


API Endpoints

Base URLs

https://your-wiki.org/w/rest.php/semanticproperty/{title}           # GET, PUT
https://your-wiki.org/w/rest.php/semanticproperty/{title}/{property} # DELETE

Subpages and Special Characters

For page titles containing slashes (subpages) or other special characters, use URL encoding:

# For "Test/SubPage" use %2F to encode the slash
curl "https://your-wiki.org/w/rest.php/semanticproperty/Test%2FSubPage"

# For "Page:Example" the colon is fine as-is
curl "https://your-wiki.org/w/rest.php/semanticproperty/Page:Example"

# For DELETE with subpage and property
curl -X DELETE "https://your-wiki.org/w/rest.php/semanticproperty/Test%2FSubPage/PropertyName"

GET - Read All Properties

Retrieve all semantic properties from a page.

Endpoint: GET /semanticproperty/{title}

Parameters: - {title}: Page title (in URL path)

Example:

curl -X GET "https://your-wiki.org/w/rest.php/semanticproperty/Page:Example"

Response:

{
  "title": "Page:Example",
  "properties": {
    "HasValue": {
      "label": "HasValue",
      "type": "quantity",
      "type_id": "_qty",      
      "values": ["42", "99"],
      "count": 2
    },
    "Has_geographic_coordinates": {
      "label": "Has_geographic_coordinates",
      "type": "geographic",
      "type_id": "_geo",
      "values": [
            {
                "latitude": 48.284152,
                "longitude": 1.021355,
                "altitude": null,
                "display": "48.284152,1.021355"
            }
        ],
      "count": 1
     },
  },
  "total_properties": 2
}

PUT - Write Property Values

Add or update semantic property values on a page.

Endpoint: PUT /semanticproperty/{title}

Authentication: Requires session authentication with edit permissions.

Parameters: - {title}: Page title (in URL path) - property (required): SMW property name (in request body) - value (required): Property value to set (in request body)

JSON Format (Recommended)

curl -X PUT "https://your-wiki.org/w/rest.php/semanticproperty/Page:Example" \
  -H "Content-Type: application/json" \
  -b cookies.txt \
  -d '{"property":"HasValue","value":"42"}'

Form Data Format

curl -X PUT "https://your-wiki.org/w/rest.php/semanticproperty/Page:Example" \
  -b cookies.txt \
  -d "property=HasValue&value=42"

Success Response:

{
  "result": "success",
  "title": "Page:Example",
  "property": "HasValue",
  "property_key": "HasValue",
  "property_label": "HasValue",
  "value": "42"
}

DELETE - Remove Property Values

Remove all values for a specific semantic property from a page.

Endpoint: DELETE /semanticproperty/{title}/{property}

Authentication: Requires session authentication with edit permissions.

Parameters: - {title}: Page title (in URL path, URL-encode slashes as %2F for subpages) - {property}: SMW property name to delete (in URL path)

Examples

# Delete from a regular page
curl -X DELETE "https://your-wiki.org/w/rest.php/semanticproperty/Page:Example/HasValue" \
  -b cookies.txt

# Delete from a subpage (note the encoded slash %2F)
curl -X DELETE "https://your-wiki.org/w/rest.php/semanticproperty/Test%2FSubPage/PropertyName" \
  -b cookies.txt

Success Response:

{
  "result": "success",
  "title": "Page:Example",
  "property": "HasValue",
  "message": "Property deleted successfully"
}

Error Responses

The API returns appropriate HTTP status codes and error messages:

Common Error Responses

400 Bad Request - Invalid parameters:

{
  "error": "Missing required parameters: title or property"
}

403 Forbidden - Permission denied:

{
  "error": "Permission denied"
}

404 Not Found - Page doesn’t exist:

{
  "error": "Page does not exist: NonExistentPage"
}

500 Internal Server Error - SMW error:

{
  "error": "SMW error: Invalid property type"
}

Authentication

Session Authentication (Required)

MediaWiki 1.43 REST API requires session-based authentication. You need to login via the Action API first, then use the session cookies for REST calls.

Step 1: Get Login Token

curl -c cookies.txt "https://your-wiki.org/w/api.php?action=query&meta=tokens&type=login&format=json"

Step 2: Login with BotPassword

curl -b cookies.txt -c cookies.txt -d "action=login&lgname=YourBot@AppName&lgpassword=BotPassword&lgtoken=TOKEN&format=json" "https://your-wiki.org/w/api.php"

Step 3: Use Session Cookies for REST API

curl -b cookies.txt -X PUT -H "Content-Type: application/json" -d '{"property":"HasValue","value":"42"}' "https://your-wiki.org/w/rest.php/semanticproperty/Page:Example"

BotPassword Setup

  1. Create a BotPassword:
    • Go to Special:BotPasswords on your wiki
    • Create a new bot password with “Edit existing pages” permission
    • Note the username format: Username@AppName
    • Save the generated password

Code Examples

PHP Example

<?php
// Read all properties from a page
$response = file_get_contents(
    "https://your-wiki.org/w/rest.php/semanticproperty/" . urlencode('Page:Example')
);
$data = json_decode($response, true);

// Write a property (requires session authentication)
// First, login to get session cookies
$loginToken = getLoginToken();
login($loginToken, 'YourBot@AppName', 'BotPassword');

// Then make authenticated request
$putData = json_encode([
    'property' => 'HasValue',
    'value' => '42'
]);

$context = stream_context_create([
    'http' => [
        'method' => 'PUT',
        'header' => [
            'Content-Type: application/json',
            'Cookie: ' . getCookies()
        ],
        'content' => $putData
    ]
]);

$response = file_get_contents('https://your-wiki.org/w/rest.php/semanticproperty/Page:Example', false, $context);
?>

JavaScript Example

// Read all properties from a page
const response = await fetch(
    'https://your-wiki.org/w/rest.php/semanticproperty/Page:Example'
);
const data = await response.json();

// Write a property (requires session authentication)
// First authenticate via Action API, then use cookies for REST calls
const writeResponse = await fetch('https://your-wiki.org/w/rest.php/semanticproperty/Page:Example', {
    method: 'PUT',
    credentials: 'include', // Include cookies
    headers: {
        'Content-Type': 'application/json'
    },
    body: JSON.stringify({
        property: 'HasValue',
        value: '42'
    })
});

// Delete a property
const deleteResponse = await fetch('https://your-wiki.org/w/rest.php/semanticproperty/Page:Example/HasValue', {
    method: 'DELETE',
    credentials: 'include'
});

Python Example

import requests
import json

# Create session to maintain cookies
session = requests.Session()

# Step 1: Get login token
token_response = session.get(
    'https://your-wiki.org/w/api.php',
    params={'action': 'query', 'meta': 'tokens', 'type': 'login', 'format': 'json'}
)
login_token = token_response.json()['query']['tokens']['logintoken']

# Step 2: Login
session.put(
    'https://your-wiki.org/w/api.php',
    data={
        'action': 'login',
        'lgname': 'YourBot@AppName',
        'lgpassword': 'BotPassword',
        'lgtoken': login_token,
        'format': 'json'
    }
)

# Step 3: Read all properties from a page
response = session.get(
    'https://your-wiki.org/w/rest.php/semanticproperty/Page:Example'
)
data = response.json()

# Step 4: Write a property
response = session.put(
    'https://your-wiki.org/w/rest.php/semanticproperty/Page:Example',
    json={'property': 'HasValue', 'value': '42'}
)

# Step 5: Delete a property
response = session.delete(
    'https://your-wiki.org/w/rest.php/semanticproperty/Page:Example/HasValue'
)

Property Types

The extension supports all standard SMW property types:

  • Text: Simple text values
  • Number: Numeric values
  • Date: Date values (various formats)
  • Boolean: Yes/No values
  • Page: Links to other pages
  • URL: Web addresses
  • Email: Email addresses
  • And more: All SMW data types are supported

Troubleshooting

Common Issues

  1. “Permission denied” errors:
    • Ensure your bot has edit permissions
    • Check that BotPassword is configured correctly
    • Verify the page isn’t protected
  2. “Invalid property” errors:
    • Make sure the property exists in SMW
    • Check property name spelling and case sensitivity
    • Ensure it’s not a system property
  3. “Page does not exist” errors:
    • Create the page first, or check the title format
    • Remember to include namespace prefixes (e.g., “Page:Example”)

Debug Mode

Add debugging to your requests by checking HTTP response codes and error messages in the JSON response.

Security Considerations

  • Always use HTTPS in production
  • Use BotPasswords instead of regular passwords
  • Limit bot permissions to only what’s needed
  • Validate all input data before making API calls
  • Consider rate limiting for high-volume usage
Category:Semantic MediaWiki extensions
Category:API extensions Category:All extensions Category:Extensions in GitHub version control Category:Extensions not in ExtensionJson Category:Extensions with manual MediaWiki version Category:Extensions without a compatibility policy Category:Extensions without an image Category:MIT licensed extensions Category:Semantic MediaWiki extensions Category:Stable extensions