Help us understand the problem. What is going on with this article?

Storyblokのdocs翻訳チャレンジその14!!!

More than 1 year has passed since last update.

この記事から翻訳されました

https://www.storyblok.com/docs/Delivery-Api/introduction

コンテンツデリバリAPI

コンテンツデリバリAPIはStoryblokのコンテンツにアクセスする最も簡単な方法です。

以下の言語について、コードのスニペットを用意しました。これを見ればどれほどシンプルかが分かるでしょう。

  • cUrl
  • C (LibCurl)
  • C# (RestSharp)
  • Go
  • Java (Unirest)
  • Java / Android (Android SDK)
  • JavaScript (XHR)
  • JavaScript (jQuery)
  • NodeJS (Native)
  • NodeJS (Request)
  • NodeJS (Unirest)
  • Objective-C (NSURL)
  • OCaml (Cohttp)
  • PHP SDK
  • PHP (cUrl)
  • PHP (HttpRequest)
  • Python (http.client) - Python 3
  • Python (requests)
  • Ruby (NET::Http)
  • Shell (wget)
  • Swift (NSURL)

cUrl

curl -X GET "https://api.storyblok.com/v1/cdn/stories/home?token=xs8KfuZGvQVOM824AFUQDQtt"

C(LibCurl)

CURL *hnd = curl_easy_init();

curl_easy_setopt(hnd, CURLOPT_CUSTOMREQUEST, "GET");
curl_easy_setopt(hnd, CURLOPT_URL, "https://api.storyblok.com/v1/cdn/stories/home?token=xs8KfuZGvQVOM824AFUQDQtt");

struct curl_slist *headers = NULL;
headers = curl_slist_append(headers, "cache-control: no-cache");
curl_easy_setopt(hnd, CURLOPT_HTTPHEADER, headers);

CURLcode ret = curl_easy_perform(hnd);

C# (RestSharp)

var client = new RestClient("https://api.storyblok.com/v1/cdn/stories/home?token=xs8KfuZGvQVOM824AFUQDQtt");
var request = new RestRequest(Method.GET);
request.AddHeader("cache-control", "no-cache");
IRestResponse response = client.Execute(request);

Go

package main

import (
    "fmt"
    "net/http"
    "io/ioutil"
)

func main() {

    url := "https://api.storyblok.com/v1/cdn/stories/home?token=xs8KfuZGvQVOM824AFUQDQtt"

    req, _ := http.NewRequest("GET", url, nil)

    req.Header.Add("cache-control", "no-cache")

    res, _ := http.DefaultClient.Do(req)

    defer res.Body.Close()
    body, _ := ioutil.ReadAll(res.Body)

    fmt.Println(res)
    fmt.Println(string(body))

}

Java (Unirest)

HttpResponse<String> response = Unirest.get("https://api.storyblok.com/v1/cdn/stories/home?token=xs8KfuZGvQVOM824AFUQDQtt")
  .header("cache-control", "no-cache")
  .asString();

Java / Android (Android SDK)

compile "com.mikepenz:storyblok-android-sdk:0.3.0@aar"
Storyblok client = Storyblok.init("your-storyblok-token");

client.getStory("fullSlug", new Storyblok.SuccessCallback<Story>() {
    @Override
    public void onResponse(final Result<Story> result) {
        //on success
    }
}, new Storyblok.ErrorCallback() {
     @Override
     public void onFailure(@Nullable IOException exception, @Nullable String response) {
         //on error
     }
});

JavaScript (XHR)

var data = null;

var xhr = new XMLHttpRequest();
xhr.withCredentials = true;

xhr.addEventListener("readystatechange", function () {
  if (this.readyState === 4) {
    console.log(this.responseText);
  }
});

xhr.open("GET", "https://api.storyblok.com/v1/cdn/stories/home?token=xs8KfuZGvQVOM824AFUQDQtt");
xhr.setRequestHeader("cache-control", "no-cache");

xhr.send(data);

JavaScript (jQuery)

var settings = {
  "async": true,
  "crossDomain": true,
  "url": "https://api.storyblok.com/v1/cdn/stories/home?token=xs8KfuZGvQVOM824AFUQDQtt",
  "method": "GET",
  "headers": {
    "cache-control": "no-cache"
  }
}

$.ajax(settings).done(function (response) {
  console.log(response);
});

NodeJS (Native)

var http = require("https");

var options = {
  "method": "GET",
  "hostname": "api.storyblok.com",
  "port": null,
  "path": "/v1/cdn/stories/home?token=xs8KfuZGvQVOM824AFUQDQtt",
  "headers": {
    "cache-control": "no-cache"
  }
};

var req = http.request(options, function (res) {
  var chunks = [];

  res.on("data", function (chunk) {
    chunks.push(chunk);
  });

  res.on("end", function () {
    var body = Buffer.concat(chunks);
    console.log(body.toString());
  });
});

req.end();

NodeJS (Request)

var request = require("request");

var options = { method: 'GET',
  url: 'https://api.storyblok.com/v1/cdn/stories/home',
  qs: { token: 'xs8KfuZGvQVOM824AFUQDQtt' },
  headers: 
   { 'cache-control': 'no-cache' } };

request(options, function (error, response, body) {
  if (error) throw new Error(error);

  console.log(body);
});

NodeJS (Unirest)

var unirest = require("unirest");

var req = unirest("GET", "https://api.storyblok.com/v1/cdn/stories/home");

req.query({
  "token": "xs8KfuZGvQVOM824AFUQDQtt"
});

req.headers({
  "cache-control": "no-cache"
});


req.end(function (res) {
  if (res.error) throw new Error(res.error);

  console.log(res.body);
});

Objective-C (NSURL)

#import <Foundation/Foundation.h>

NSDictionary *headers = @{ @"cache-control": @"no-cache" };

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"https://api.storyblok.com/v1/cdn/stories/home?token=xs8KfuZGvQVOM824AFUQDQtt"]
                                                       cachePolicy:NSURLRequestUseProtocolCachePolicy
                                                   timeoutInterval:10.0];
[request setHTTPMethod:@"GET"];
[request setAllHTTPHeaderFields:headers];

NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request
                                            completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
                                                if (error) {
                                                    NSLog(@"%@", error);
                                                } else {
                                                    NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *) response;
                                                    NSLog(@"%@", httpResponse);
                                                }
                                            }];
[dataTask resume];

OCaml (Cohttp)

open Cohttp_lwt_unix
open Cohttp
open Lwt

let uri = Uri.of_string "https://api.storyblok.com/v1/cdn/stories/home?token=xs8KfuZGvQVOM824AFUQDQtt" in
let headers = Header.init ()
  |> fun h -> Header.add h "cache-control" "no-cache"
in

Client.call ~headers `GET uri
>>= fun (res, body_stream) ->
  (* Do stuff with the result *)

PHP (client library)

PHPであれば私たちのphp-client libraryが使えます。

composer require storyblok/php-client dev-master
// Require composer autoload
require 'vendor/autoload.php';

// Initialize
$client = new \Storyblok\Client('xs8KfuZGvQVOM824AFUQDQtt');

// Optionally set a cache
$client->setCache('filesytem', array('path' => 'cache'));

// Get the story as array
$client->getStoryBySlug('home');
$data = $client->getBody();

もしくは、以下のスニペットを使うこともできます。

PHP (cUrl)

<?php

$curl = curl_init();

curl_setopt_array($curl, array(
  CURLOPT_URL => "https://api.storyblok.com/v1/cdn/stories/home?token=xs8KfuZGvQVOM824AFUQDQtt",
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_ENCODING => "",
  CURLOPT_MAXREDIRS => 10,
  CURLOPT_TIMEOUT => 30,
  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  CURLOPT_CUSTOMREQUEST => "GET",
  CURLOPT_HTTPHEADER => array(
    "cache-control: no-cache"
  ),
));

$response = curl_exec($curl);
$err = curl_error($curl);

curl_close($curl);

if ($err) {
  echo "cURL Error #:" . $err;
} else {
  echo $response;
}

PHP (HttpRequest)

<?php

$request = new HttpRequest();
$request->setUrl('https://api.storyblok.com/v1/cdn/stories/home');
$request->setMethod(HTTP_METH_GET);

$request->setQueryData(array(
  'token' => 'xs8KfuZGvQVOM824AFUQDQtt'
));

$request->setHeaders(array(
  'cache-control' => 'no-cache'
));

try {
  $response = $request->send();

  echo $response->getBody();
} catch (HttpException $ex) {
  echo $ex;
}

Python (http.client) - Python 3

import http.client

conn = http.client.HTTPSConnection("api.storyblok.com")

headers = {
    'cache-control': "no-cache"
    }

conn.request("GET", "/v1/cdn/stories/home?token=xs8KfuZGvQVOM824AFUQDQtt", headers=headers)

res = conn.getresponse()
data = res.read()

print(data.decode("utf-8"))

Python (requests)

import requests

url = "https://api.storyblok.com/v1/cdn/stories/home"

querystring = {"token":"xs8KfuZGvQVOM824AFUQDQtt"}

headers = {
    'cache-control': "no-cache"
    }

response = requests.request("GET", url, headers=headers, params=querystring)

print(response.text)

Ruby (NET::Http)

require 'uri'
require 'net/http'

url = URI("https://api.storyblok.com/v1/cdn/stories/home?token=xs8KfuZGvQVOM824AFUQDQtt")

http = Net::HTTP.new(url.host, url.port)
http.use_ssl = true
http.verify_mode = OpenSSL::SSL::VERIFY_NONE

request = Net::HTTP::Get.new(url)
request["cache-control"] = 'no-cache'

response = http.request(request)
puts response.read_body

Shell (wget)

wget --quiet \
  --method GET \
  --header 'cache-control: no-cache' \
  --output-document \
  - 'https://api.storyblok.com/v1/cdn/stories/home?token=xs8KfuZGvQVOM824AFUQDQtt'

Swift (NSURL)

import Foundation

let headers = [
  "cache-control": "no-cache"
]

let request = NSMutableURLRequest(url: NSURL(string: "https://api.storyblok.com/v1/cdn/stories/home?token=xs8KfuZGvQVOM824AFUQDQtt")! as URL,
                                        cachePolicy: .useProtocolCachePolicy,
                                    timeoutInterval: 10.0)
request.httpMethod = "GET"
request.allHTTPHeaderFields = headers

let session = URLSession.shared
let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in
  if (error != nil) {
    print(error)
  } else {
    let httpResponse = response as? HTTPURLResponse
    print(httpResponse)
  }
})

dataTask.resume()

探しものが見つかりませんか?Stackoverflowであなたのケースを私たちに質問してください。何かが足りないと感じていて、もしそれをここに追加したければ、pull requestGitHubで発行して下さい。追加します。

si-gma
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away