LoginSignup
2
1

More than 1 year has passed since last update.

いろいろな言語のAPIコール

Last updated at Posted at 2021-11-25

導入

webAPIの叩き方を各言語でまとめました。
後で見返す用です。
2021年11月23日時点:Postリクエスト送信

json リクエストのサンプルパラメータ

sample_endpoint = "http://localhost:8888/sample"
sample_parameter = {
    "title": "トマトスープ",
    "making_time": "15分",
    "serves": "5人",
    "ingredients": "玉ねぎ, トマト, スパイス, 水",
    "cost": "450"
}

Curl

curl --location --request POST 'http://localhost:8888/recipes' \
--header 'Content-Type: application/json' \
--data-raw '{
    "title": "トマトスープ",
    "making_time": "15分",
    "serves": "5人",
    "ingredients": "玉ねぎ, トマト, スパイス, 水",
    "cost": "450"
}'

Go

package main

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

func main() {

  url := "http://localhost:8888/recipes"
  method := "POST"

  payload := strings.NewReader(`{
    "title": "トマトスープ",
    "making_time": "15分",
    "serves": "5人",
    "ingredients": "玉ねぎ, トマト, スパイス, 水",
    "cost": "450"
}`)

  client := &http.Client {
  }
  req, err := http.NewRequest(method, url, payload)

  if err != nil {
    fmt.Println(err)
    return
  }
  req.Header.Add("Content-Type", "application/json")

  res, err := client.Do(req)
  if err != nil {
    fmt.Println(err)
    return
  }
  defer res.Body.Close()

  body, err := ioutil.ReadAll(res.Body)
  if err != nil {
    fmt.Println(err)
    return
  }
  fmt.Println(string(body))
}

php

<?php
require_once 'HTTP/Request2.php';
$request = new HTTP_Request2();
$request->setUrl('http://localhost:8888/recipes');
$request->setMethod(HTTP_Request2::METHOD_POST);
$request->setConfig(array(
  'follow_redirects' => TRUE
));
$request->setHeader(array(
  'Content-Type' => 'application/json'
));
$request->setBody('{\n    "title": "トマトスープ",\n    "making_time": "15分",\n    "serves": "5人",\n    "ingredients": "玉ねぎ, トマト, スパイス, 水",\n    "cost": "450"\n}');
try {
  $response = $request->send();
  if ($response->getStatus() == 200) {
    echo $response->getBody();
  }
  else {
    echo 'Unexpected HTTP status: ' . $response->getStatus() . ' ' .
    $response->getReasonPhrase();
  }
}
catch(HTTP_Request2_Exception $e) {
  echo 'Error: ' . $e->getMessage();
}

python

import requests
import json

url = "http://localhost:8888/recipes"

payload = json.dumps({
  "title": "トマトスープ",
  "making_time": "15分",
  "serves": "5人",
  "ingredients": "玉ねぎ, トマト, スパイス, 水",
  "cost": "450"
})
headers = {
  'Content-Type': 'application/json'
}

response = requests.request("POST", url, headers=headers, data=payload)

print(response.text)

これから

getパラメータの記述方法なども追記していく

2
1
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1