API:REST API/Reference/Sample code:Create page
< API:REST API | Reference
curl[edit]
# Create a user sandbox page on English Wikipedia
$ curl -X POST https://en.wikipedia.org/w/rest.php/v1/page -H "Content-Type: application/json" -H "Authorization: Bearer $TOKEN" --data '{"source": "Hello, world!", "title": "User:<my username>/Sandbox", "comment": "Creating a test page with the REST API"}'
Python[edit]
# Create a user sandbox page on English Wikipedia
import requests
import json
url = 'https://en.wikipedia.org/w/rest.php/v1/page'
# Substitute your OAuth token
headers = {
'User-Agent' : 'MediaWiki REST API docs examples/0.1 (https://www.mediawiki.org/wiki/API_talk:REST_API)',
'Content-Type' : 'application/json',
'Authorization': 'Bearer $TOKEN'
}
# Substitute your username
request_data = {
"source" : "Hello, world!",
"title" : "User:<my username>/Sandbox",
"comment": "Creating a test page with the REST API"
}
response = requests.post( url, headers=headers, data = json.dumps(request_data) )
output = response.json()
print(output)
PHP[edit]
<?php
/*
Create a user sandbox page on English Wikipedia
*/
$url = 'https://en.wikipedia.org/w/rest.php/v1/page';
// Substitute your username
$fields = [
'source' => 'Hello, world!',
'title' => 'User:<my username>/Sandbox',
'comment' => 'Creating a test page with the REST API'
];
$json = json_encode( $fields );
$token = 'YOUR_OAUTH_TOKEN'; // Substitute your OAuth token
$authorization = 'Authorization: Bearer ' . $token;
$ch = curl_init();
curl_setopt( $ch, CURLOPT_URL, $url );
curl_setopt( $ch, CURLOPT_POST, true );
curl_setopt( $ch, CURLOPT_POSTFIELDS, $json );
curl_setopt( $ch, CURLOPT_HTTPHEADER, array( 'Content-Type: application/json' , $authorization ));
curl_setopt( $ch, CURLOPT_USERAGENT, 'MediaWiki REST API docs examples/0.1 (https://www.mediawiki.org/wiki/API_talk:REST_API)' );
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
$output = curl_exec( $ch );
curl_close( $ch );
echo( $output );
?>
JavaScript[edit]
/*
Create a user sandbox page on English Wikipedia
Substitute your OAuth token for $TOKEN.
Substitute your username for <my username>.
*/
async function doFetch() {
const response = await fetch(
"https://en.wikipedia.org/w/rest.php/v1/page",
{
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer $TOKEN'
},
body: JSON.stringify({
"source" : "Hello, world!",
"title" : "User:<my username>/Sandbox",
"comment": "Creating a test page with the REST API"
}),
'Api-User-Agent': 'MediaWiki REST API docs examples/0.1 (https://www.mediawiki.org/wiki/API_talk:REST_API)'
}
);
const data = await response.json();
return data;
}
async function fetchAsync()
{
try {
let result = await doFetch();
console.log(result);
} catch( err ) {
console.error( err.message );
}
}
fetchAsync();