mixi Developer Center (ミクシィ デベロッパーセンター)

mixiアプリ

mixiアプリ » 技術仕様(RESTful API方式) » モバイル » RESTful APIサンプルコード » Persistence API

Persistence API

ユーザに関するデータをサーバ上に保存/取得します。

PHP

<?php
require_once('OAuth.php');

// Establish an OAuth consumer based on our admin 'credentials'
$CONSUMER_KEY = 'YOUR_CONSUMER_KEY';
$CONSUMER_SECRET = 'YOUR_CONSUMER_SECRET';
$consumer = new OAuthConsumer($CONSUMER_KEY, $CONSUMER_SECRET, NULL);

// Setup OAuth request based our previous credentials and query
$user= 'xxxxxxxx';
$base_feed = 'http://api.mixi-platform.com/os/0.8/appdata/@me/@self/@app';
$params = array('xoauth_requestor_id' => $user);
$request = OAuthRequest::from_consumer_and_token($consumer, NULL, 'POST', $base_feed, $params);
$postData = <<<EOD
{"point": 97,
 "class": "Dark Knight"
}
EOD;

// Sign the constructed OAuth request using HMAC-SHA1
$request->sign_request(new OAuthSignatureMethod_HMAC_SHA1(), $consumer, NULL);

// Make signed OAuth request to the Contacts API server
$url = $base_feed . '?' . implode_assoc('=', '&', $params);
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_FAILONERROR, false);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);

$auth_header = $request->to_header();
curl_setopt($curl, CURLOPT_HTTPHEADER,
            array('Content-Type: application/json', $auth_header));
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, $postData);
$response = curl_exec($curl);

$request = OAuthRequest::from_consumer_and_token($consumer, NULL, 'GET', $base_feed, $params);

// Sign the constructed OAuth request using HMAC-SHA1
$request->sign_request(new OAuthSignatureMethod_HMAC_SHA1(), $consumer, NULL);

// Make signed OAuth request to the Contacts API server
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_FAILONERROR, false);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);

$auth_header = $request->to_header();
if ($auth_header) {
  curl_setopt($curl, CURLOPT_HTTPHEADER, array($auth_header));
}

$response = curl_exec($curl);
if (!$response) {
  $response = curl_error($curl);
}
curl_close($curl);

var_dump($response);

/**
 * Joins key:value pairs by inner_glue and each pair together by outer_glue
 * @param string $inner_glue The HTTP method (GET, POST, PUT, DELETE)
 * @param string $outer_glue Full URL of the resource to access
 * @param array $array Associative array of query parameters
 * @return string Urlencoded string of query parameters
 */
function implode_assoc($inner_glue, $outer_glue, $array) {
  $output = array();
  foreach($array as $key => $item) {
    $output[] = $key . $inner_glue . urlencode($item);
  }
  return implode($outer_glue, $output);
}
?>

※古いバージョンの OAuth.php には不具合が発見されています。
上記のサンプルプログラムがうまく動作しない場合は、最新版をダウンロードして試してみてください。

Python

#!/usr/bin/env python
import urllib, urllib2
import oauth

CONSUMER_KEY = 'YOUR_CONSUMER_KEY'
CONSUMER_SECRET = 'YOUR_CONSUMER_SECRET'
BASE_URL = 'http://api.mixi-platform.com/os/0.8'

# Setup 2 legged OAuth consumer based
consumer = oauth.OAuthConsumer(CONSUMER_KEY, CONSUMER_SECRET)

params = {'xoauth_requestor_id': 'xxxxxxxx'}

def create_appdata():
    request = oauth.OAuthRequest.from_consumer_and_token(
                  consumer,
                  http_method = 'POST',
                  http_url = BASE_URL + '/appdata/@me/@self/@app',
                  parameters = params,
              )
    request.sign_request(oauth.OAuthSignatureMethod_HMAC_SHA1(), consumer, None)
    json = '{"point":97, "class":"Dark Knight"}'

    uri = '%s?%s' % (request.http_url, urllib.urlencode(params))
    r = urllib2.Request(uri, json, request.to_header())
    r.add_header('Content-Type', 'application/json')

    return urllib2.urlopen(r)

def read_appdata(fields):
    p = params
    p['fields'] = fields

    request = oauth.OAuthRequest.from_consumer_and_token(
                  consumer,
                  http_method = 'GET',
                  http_url = BASE_URL + '/appdata/@me/@self/@app',
                  parameters = p,
              )
    request.sign_request(oauth.OAuthSignatureMethod_HMAC_SHA1(), consumer, None)

    uri = '%s?%s' % (request.http_url, urllib.urlencode(params))
    r = urllib2.Request(uri, headers=request.to_header())

    return urllib2.urlopen(r)

def update_appdata():
    request = oauth.OAuthRequest.from_consumer_and_token(
                  consumer,
                  http_method = 'PUT',
                  http_url = BASE_URL + '/appdata/@me/@self/@app',
                  parameters = params,
              )
    request.sign_request(oauth.OAuthSignatureMethod_HMAC_SHA1(), consumer, None)
    json = '{"point":60}'

    uri = '%s?%s' % (request.http_url, urllib.urlencode(params))
    r = urllib2.Request(uri, json, request.to_header())
    r.add_header('Content-Type', 'application/json')
    r.get_method = lambda: 'PUT'

    return urllib2.urlopen(r)

def delete_appdata(fields):
    p = params
    p['fields'] = fields

    request = oauth.OAuthRequest.from_consumer_and_token(
                  consumer,
                  http_method = 'DELETE',
                  http_url = BASE_URL + '/appdata/@me/@self/@app',
                  parameters = p,
              )
    request.sign_request(oauth.OAuthSignatureMethod_HMAC_SHA1(), consumer, None)

    uri = '%s?%s' % (request.http_url, urllib.urlencode(params))
    r = urllib2.Request(uri, headers=request.to_header())
    r.get_method = lambda: 'DELETE'

    return urllib2.urlopen(r)

try:
    create_appdata()
    read_appdata('*')

    update_appdata()
    read_appdata('point')

    delete_appdata('*')
    read_appdata('*')
except urllib2.HTTPError, e:
    print e

Perl

use 5.0.8;

use strict;
use warnings;

use Data::Dumper;
use JSON::XS;
use Time::HiRes;
use OAuth::Lite;
use OAuth::Lite::Consumer;

my %options = (
    site            => 'api.mixi-platform.com',
    consumer_key    => 'YOUR_CONSUMER_KEY',
    consumer_secret => 'YOUR_CONSUMER_SECRET',
    requester_id    => 'xxxxxxxx',
);

my $endpoint = sprintf('http://%s/os/0.8/appdata/@me/@self/@app', $options{site});
my $consumer = OAuth::Lite::Consumer->new(
    consumer_key    => $options{consumer_key},
    consumer_secret => $options{consumer_secret});

sub create_appdata {
    my ($appdata) = @_;

    my $response = $consumer->request(
        method  => 'POST',
        url     => $endpoint,
        params  => {
            xoauth_requestor_id => $options{requester_id},
        },

        headers => [ 'Content-Type' => 'application/json' ],
        content => JSON::XS::encode_json($appdata));

    $response->is_success or die 'Unable to create appdata: ' . $response->status_line;
}

sub read_appdata {
    my @fields = @_;

    my $response = $consumer->request(
        method  => 'GET',
        url     => $endpoint,
        params  => {
            format => 'json',
            xoauth_requestor_id => $options{requester_id},
            fields              => join(',', @fields),
        });

    $response->is_success or die 'Unable to read appdata: ' . $response->status_line;
    return $response;

    #my $content = JSON::XS::decode_json($response->decoded_content);
    #my $guid    = $content->{id}[0];

    #return defined($guid) ? $content->{entry}{$guid}
    #                      : {};
}

sub update_appdata {
    my ($appdata) = @_;

    my $response = $consumer->request(
        method  => 'PUT',
        url     => $endpoint,
        params  => {
            xoauth_requestor_id => $options{requester_id},
        },

        headers => [ 'Content-Type' => 'application/json' ],
        content => JSON::XS::encode_json($appdata));

    $response->is_success or die 'Unable to update appdata: ' . $response->status_line;
}

sub delete_appdata {
    my @fields = @_;

    my $response = $consumer->request(
        method  => 'DELETE',
        url     => $endpoint,
        params  => {
            xoauth_requestor_id => $options{requester_id},
            fields              => join(',', @fields),
        });

    $response->is_success or die 'Unable to delete appdata: ' . $response->status_line;
}

## CRUD
create_appdata({
    subject => 'appdata subject: ' . int(rand(100)),
    content => 'appdata content: ' . int(rand(100)),
    updated => sprintf('%d:%d', Time::HiRes::gettimeofday),
});
print 'create appdata: ' . Dumper(read_appdata('*'));

update_appdata({
    updated => sprintf('%d:%d', Time::HiRes::gettimeofday),
});
print 'update appdata: ' . Dumper(read_appdata('updated'));

delete_appdata('*');
print 'delete appdata: ' . Dumper(read_appdata(qw(subject content updated)));

このページの上部へ