Below is a collection of different HTTP clients in the following language:
axios.get('/user', {
params: {
ID: 12345
}
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
})
.then(function () {
// always executed
});
Source: https://github.com/axios/axios
$.ajax({
url: "https://fiddle.jshell.net/favicon.png",
beforeSend: function( xhr ) {
xhr.overrideMimeType( "text/plain; charset=x-user-defined" );
}
})
.done(function( data ) {
if ( console && console.log ) {
console.log( "Sample of data:", data.slice( 0, 100 ) );
}
});
Source: https://api.jquery.com/jQuery.ajax/
fetch('http://example.com/movies.json')
.then(function(response) {
return response.json();
})
.then(function(myJson) {
console.log(JSON.stringify(myJson));
});
Source: https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch
const request = require('request');
request.post({
url:'http://service.com/upload', form: {key:'value'}
}, function(err,httpResponse,body){ /* ... */ }
)
request('https://api.nasa.gov/planetary/apod?api_key=DEMO_KEY', { json: true }, (err, res, body) => {
if (err) { return console.log(err); }
console.log(body.url);
console.log(body.explanation);
});
Source: https://github.com/request/request#forms
const https = require('https');
https.get('https://api.nasa.gov/planetary/apod?api_key=DEMO_KEY', (resp) => {
let data = '';
// A chunk of data has been recieved.
resp.on('data', (chunk) => {
data += chunk;
});
// The whole response has been received. Print out the result.
resp.on('end', () => {
console.log(JSON.parse(data).explanation);
});
}).on("error", (err) => {
console.log("Error: " + err.message);
});
Source: https://nodejs.org/api/http.html#http_http_get_options_callback
const superagent = require('superagent');
// callback
superagent
.post('/api/pet')
.send({ name: 'Manny', species: 'cat' }) // sends a JSON post body
.set('X-API-Key', 'foobar')
.set('accept', 'json')
.end((err, res) => {
// Calling the end function will send the request
});
// promise with then/catch
superagent.post('/api/pet').then(console.log).catch(console.error);
// promise with async/await
(async () => {
try {
const res = await superagent.post('/api/pet');
console.log(res);
} catch (err) {
console.error(err);
}
})();
Source: https://github.com/visionmedia/superagent#node
const got = require('got');
got('https://api.nasa.gov/planetary/apod?api_key=DEMO_KEY', { json: true }).then(response => {
console.log(response.body.url);
console.log(response.body.explanation);
}).catch(error => {
console.log(error.response.body);
});
And working with stream
const fs = require('fs');
const got = require('got');
got.stream('https://sindresorhus.com').pipe(fs.createWriteStream('index.html'));
// For POST, PUT, and PATCH methods `got.stream` returns a `stream.Writable`
fs.createReadStream('index.html').pipe(got.stream.post('https://sindresorhus.com'));
Source: https://github.com/sindresorhus/got#streams
import requests
resp = requests.get('https://todolist.example.com/tasks/')
if resp.status_code != 200:
# This means something went wrong.
raise ApiError('GET /tasks/ {}'.format(resp.status_code))
for todo_item in resp.json():
print('{} {}'.format(todo_item['id'], todo_item['summary']))
Source: https://realpython.com/api-integration-in-python/
// Execute a GET with timeout settings and return response content as String.
Request.Get("http://somehost/")
.connectTimeout(1000)
.socketTimeout(1000)
.execute().returnContent().asString();
// Execute a POST with the 'expect-continue' handshake, using HTTP/1.1,
// containing a request body as String and return response content as byte array.
Request.Post("http://somehost/do-stuff")
.useExpectContinue()
.version(HttpVersion.HTTP_1_1)
.bodyString("Important stuff", ContentType.DEFAULT_TEXT)
.execute().returnContent().asBytes();
Source: https://hc.apache.org/httpcomponents-client-ga/tutorial/html/fluent.html
public static String executePost(String targetURL, String urlParameters) {
HttpURLConnection connection = null;
try {
//Create connection
URL url = new URL(targetURL);
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
connection.setRequestProperty("Content-Length",
Integer.toString(urlParameters.getBytes().length));
connection.setRequestProperty("Content-Language", "en-US");
connection.setUseCaches(false);
connection.setDoOutput(true);
//Send request
DataOutputStream wr = new DataOutputStream (
connection.getOutputStream());
wr.writeBytes(urlParameters);
wr.close();
//Get Response
InputStream is = connection.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
StringBuilder response = new StringBuilder(); // or StringBuffer if Java version 5+
String line;
while ((line = rd.readLine()) != null) {
response.append(line);
response.append('\r');
}
rd.close();
return response.toString();
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
if (connection != null) {
connection.disconnect();
}
}
}
Source: https://stackoverflow.com/a/1359700
Source: https://www.twilio.com/blog/2015/10/4-ways-to-parse-a-json-api-with-ruby.html
require 'net/http'
require 'json'
url = 'https://api.spotify.com/v1/search?type=artist&q=tycho'
uri = URI(url)
response = Net::HTTP.get(uri)
JSON.parse(response)
require 'httparty'
url = 'https://api.spotify.com/v1/search?type=artist&q=tycho'
response = HTTParty.get(url)
response.parsed_response
require 'faraday'
require 'faraday_middleware'
url = 'https://api.spotify.com/v1'
conn = Faraday.new(url: url) do |faraday|
faraday.adapter Faraday.default_adapter
faraday.response :json
end
response = conn.get('search', type: 'artist', q: 'tycho')
response.body
# Output debug info, similar to ENV['EXCON_DEBUG']
connection = Excon.new('http://geemus.com/', :debug_request => true, :debug_response => true)
# Custom headers
Excon.get('http://geemus.com', :headers => {'Authorization' => 'Basic 0123456789ABCDEF'})
connection.get(:headers => {'Authorization' => 'Basic 0123456789ABCDEF'})
# Changing query strings
connection = Excon.new('http://geemus.com/')
connection.get(:query => {:foo => 'bar'})
# POST body encoded with application/x-www-form-urlencoded
Excon.post('http://geemus.com',
:body => 'language=ruby&class=fog',
:headers => { "Content-Type" => "application/x-www-form-urlencoded" })
# same again, but using URI to build the body of parameters
Excon.post('http://geemus.com',
:body => URI.encode_www_form(:language => 'ruby', :class => 'fog'),
:headers => { "Content-Type" => "application/x-www-form-urlencoded" })
Source: https://github.com/excon/excon#options
<?php
$homepage = file_get_contents('http://www.example.com/');
echo $homepage;
?>
<?php
$r = new HttpRequest('http://example.com/feed.rss', HttpRequest::METH_GET);
$r->setOptions(array('lastmodified' => filemtime('local.rss')));
$r->addQueryData(array('category' => 3));
try {
$r->send();
if ($r->getResponseCode() == 200) {
file_put_contents('local.rss', $r->getResponseBody());
}
} catch (HttpException $ex) {
echo $ex;
}
?>
$client = new GuzzleHttp\Client();
$res = $client->request('GET', 'https://api.github.com/user', [
'auth' => ['user', 'pass']
]);
echo $res->getStatusCode();
// "200"
echo $res->getHeader('content-type')[0];
// 'application/json; charset=utf8'
echo $res->getBody();
// {"type":"User"...'
// Send an asynchronous request.
$request = new \GuzzleHttp\Psr7\Request('GET', 'http://httpbin.org');
$promise = $client->sendAsync($request)->then(function ($response) {
echo 'I completed! ' . $response->getBody();
});
$promise->wait();
Source: https://guzzle.readthedocs.io/en/latest/
<?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'www.someapi.com?param1=A¶m2=B');
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-type: application/json')); // Assuming you're requesting JSON
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$response = curl_exec($ch);
// If using JSON...
$data = json_decode($response);
?>
#include <iostream>
#include <string>
#include <curl/curl.h> //your directory may be different
using namespace std;
string data; //will hold the url's contents
size_t writeCallback(char* buf, size_t size, size_t nmemb, void* up)
{ //callback must have this declaration
//buf is a pointer to the data that curl has for us
//size*nmemb is the size of the buffer
for (int c = 0; c<size*nmemb; c++)
{
data.push_back(buf[c]);
}
return size*nmemb; //tell curl how many bytes we handled
}
int main()
{
CURL* curl; //our curl object
curl_global_init(CURL_GLOBAL_ALL); //pretty obvious
curl = curl_easy_init();
curl_easy_setopt(curl, CURLOPT_URL, "http://www.example.com/path");
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, &writeCallback);
curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L); //tell curl to output its progress
curl_easy_perform(curl);
cout << endl << data << endl;
cin.get();
curl_easy_cleanup(curl);
curl_global_cleanup();
return 0;
}
Source: http://www.cplusplus.com/forum/unices/45878/
#include <cpr/cpr.h>
int main(int argc, char** argv) {
auto r = cpr::Get(cpr::Url{"https://api.github.com/repos/whoshuu/cpr/contributors"},
cpr::Authentication{"user", "pass"},
cpr::Parameters{{"anon", "true"}, {"key", "value"}});
r.status_code; // 200
r.header["content-type"]; // application/json; charset=utf-8
r.text; // JSON text string
}
Source: https://github.com/whoshuu/cpr#c-requests-curl-for-people-
package main
import (
"fmt"
"io/ioutil"
"net/http"
)
func main() {
APIURL := "https://httpbin.org/get"
req, err := http.NewRequest(http.MethodGet, APIURL, nil)
if err != nil {
panic(err)
}
client := http.DefaultClient
resp, err := client.Do(req)
if err != nil {
panic(err)
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
panic(err)
}
fmt.Printf("%v", string(body))
}
Source: https://dev.to/shindakun/attempting-to-learn-go---consuming-a-rest-api-5c7g
# First, we should start `inets` application.
# `httpc` is part of it:
Application.ensure_all_started(:inets)
# We should start `ssl` application also,
# if we want to make secure requests:
Application.ensure_all_started(:ssl)
# Now we can make request:
{:ok, {{'HTTP/1.1', 200, 'OK'}, _headers, _body} =
:httpc.request(:get, {'http://google.com', []}, [], [])
# `httpc` will follow redirect from `http` to `https` without
# additional config.
Source: https://virviil.github.io/2018/04/06/elixir-do-you-have-http-requests-you-are-doing-them-wrong/
% Make a GET request
Method = get,
URL = <<"https://friendpaste.com">>,
Headers = [],
Payload = <<>>,
Options = [],
{ok, StatusCode, RespHeaders, ClientRef} = hackney:request(Method, URL,
Headers, Payload,
Options).
% Make a POST request
ReqBody = << "{ \"snippet\": \"some snippet\" }" >>,
ReqHeaders = [{<<"Content-Type">>, <<"application/json">>}],
NextPath = <<"/">>,
NextMethod = post,
NextReq = {NextMethod, NextPath, ReqHeaders, ReqBody},
{ok, _, _, ConnRef} = hackney:send_request(ConnRef, NextReq),
{ok, Body1} = hackney:body(ConnRef).
Source: https://github.com/benoitc/hackney
6> ibrowse:send_req("http://intranet/messenger/", [], get).
{ok,"200",
[{"Server","Microsoft-IIS/5.0"},
{"Content-Location","http://intranet/messenger/index.html"},
{"Date","Fri, 17 Dec 2004 15:16:19 GMT"},
{"Content-Type","text/html"},
{"Accept-Ranges","bytes"},
{"Last-Modified","Fri, 17 Dec 2004 08:38:21 GMT"},
{"Etag","\"aa7c9dc313e4c41:d77\""},
{"Content-Length","953"}],
"<html>...</html>"}
Source: https://github.com/cmullaparthi/ibrowse#synchronous-requests