Examples of calling an API HTTP GET for JSON in different languages
17 Feb 2019Downloading JSON via GET from a simple API should be the 2nd tutorial right after Hello World for every language. Below is an ever-growing collection of code examples to highlight the differences in different programming languages and serve as a practical reference.
Jump to an implementation:
- Node.js
- Javascript
- Deno
- PHP
- Java
- Groovy
- C#
- Objective C
- Go
- Ruby
- Python
- Perl
- Dart
- Swift
- Rust
- Powershell
- Shell
Contribution Rules/Guidelines
- no 3rd party libraries/packages/modules allowed (unless required for HTTPS)
- must be making an HTTPS request and use endpoint: https://swapi.co/api/people/1/
- keep it simple and readable
- its ok to ignore errors and best practices
- when practical/terse include the code to parse JSON too
Please contribute (pull request) if you have a better approach or a new language.
Node.js HTTP GET
See https
var https = require('https');
var options = {
host: 'swapi.co',
path: '/api/people/1/',
headers: {
'Accept': 'application/json'
}
};
https.get(options, function (res) {
var json = '';
res.on('data', function (chunk) {
json += chunk;
});
res.on('end', function () {
if (res.statusCode === 200) {
try {
var data = JSON.parse(json);
// data is available here:
console.log(json);
} catch (e) {
console.log('Error parsing JSON!');
}
} else {
console.log('Status:', res.statusCode);
}
});
}).on('error', function (err) {
console.log('Error:', err);
});
Javascript HTTP GET
Below is a sync example using XMLHttpRequest. From StackOverflow: HTTP GET request in JavaScript
var req = new XMLHttpRequest();
req.open('GET', 'https://swapi.co/api/people/1/', false);
req.send(null);
console.log(req.responseText);
Deno HTTP GET
Deno is a "simple, modern and secure runtime for JavaScript and TypeScript that uses V8 and is built in Rust."
You will need to use --allow-net
to allow network access.
// Name the below go.ts
// Then run with: deno run --allow-net go.ts https://jsonplaceholder.typicode.com/todos/
const url = Deno.args[0];
const res = await fetch(url);
const items = await res.json();
console.log(items);
PHP HTTP GET
json_decode and filegetcontents. Source
$json = file_get_contents('https://swapi.co/api/people/1/');
echo $json;
$obj = json_decode($json);
Java HTTP GET
I don't know Java. Is this really the most simple way without 3rd party packages? Source
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.URL;
import java.nio.charset.Charset;
import org.json.JSONException;
import org.json.JSONObject;
public class JsonReader {
private static String readAll(Reader rd) throws IOException {
StringBuilder sb = new StringBuilder();
int cp;
while ((cp = rd.read()) != -1) {
sb.append((char) cp);
}
return sb.toString();
}
public static JSONObject readJsonFromUrl(String url) throws IOException, JSONException {
InputStream is = new URL(url).openStream();
try {
BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
String jsonText = readAll(rd);
JSONObject json = new JSONObject(jsonText);
return json;
} finally {
is.close();
}
}
public static void main(String[] args) throws IOException, JSONException {
JSONObject json = readJsonFromUrl("https://swapi.co/api/people/1/");
System.out.println(json.toString());
System.out.println(json.get("id"));
}
}
Groovy HTTP GET
Apache Groovy is a Java-syntax-compatible object-oriented programming language for the Java platform. Source
def connection = new URL( "https://swapi.co/api/people/1/")
.openConnection() as HttpURLConnection
connection.setRequestProperty( 'Accept', 'application/json' )
// get the response code - automatically sends the request
println connection.inputStream.text
C# HTTP GET
With WebClient. Code Source
using (WebClient wc = new System.Net.WebClient())
{
var json = wc.DownloadString("https://swapi.co/api/people/1/");
}
or an async and HttpClient
using (var httpClient = new System.Net.Http.HttpClient())
{
var json = await httpClient.GetStringAsync("https://swapi.co/api/people/1/");
}
Objective C and Cocoa HTTP GET
// making a GET request to /init
NSString *targetUrl = @"https://swapi.co/api/people/1/";
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setHTTPMethod:@"GET"];
[request setURL:[NSURL URLWithString:targetUrl]];
[[[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:
^(NSData * _Nullable data,
NSURLResponse * _Nullable response,
NSError * _Nullable error) {
NSString *myString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(@"Data received: %@", myString);
}] resume];
Go programming language - Golang HTTP GET
package main
import (
"fmt"
"net/http"
"io/ioutil"
"os"
)
func main() {
response, err := http.Get("https://swapi.co/api/people/1/")
if err != nil {
fmt.Printf("%s", err)
os.Exit(1)
} else {
defer response.Body.Close()
contents, err := ioutil.ReadAll(response.Body)
if err != nil {
fmt.Printf("%s", err)
os.Exit(1)
}
fmt.Printf("%s\n", string(contents))
}
}
Ruby HTTP GET
require 'net/http'
require 'json'
url = 'https://swapi.co/api/people/1/'
uri = URI(url)
response = Net::HTTP.get(uri)
JSON.parse(response)
Python HTTP GET
import requests
r = requests.get('https://swapi.co/api/people/1/')
r.json()
Tested with Python 2.7.12.
Perl HTTP GET
#!/usr/bin/perl
use LWP::UserAgent;
use HTTP::Request;
my $URL = 'https://swapi.co/api/people/1/';
my $ua = LWP::UserAgent->new(ssl_opts => { verify_hostname => 1 });
my $header = HTTP::Request->new(GET => $URL);
my $request = HTTP::Request->new('GET', $URL, $header);
my $response = $ua->request($request);
if ($response->is_success){
print "URL:$URL\nHeaders:\n";
print $response->headers_as_string;
}elsif ($response->is_error){
print "Error:$URL\n";
print $response->error_as_HTML;
}
For http (non https) it can be simply be:
#!/usr/bin/perl
use LWP::Simple;
my $content = get('http://jsonplaceholder.typicode.com/todos/1');
print $content
Dart HTTP GET
Dart is "an object-oriented, class defined, garbage-collected language using a C-style syntax that transcompiles optionally into JavaScript." - Wikipedia. Code Source
import 'dart:io';
import 'dart:convert';
void main() {
HttpClient()
.getUrl(Uri.parse('https://swapi.co/api/people/1/')) // produces a request object
.then((request) => request.close()) // sends the request
.then((response) => response.transform(Utf8Decoder()).listen(print)); // transforms and prints the response
}
Swift HTTP GET
Swift is a "general-purpose, multi-paradigm, compiled programming language developed by Apple." -Wikipedia. Code Source.
let url = URL(string: "https://swapi.co/api/people/1/")!
let task = URLSession.shared.dataTask(with: url) {(data, response, error) in
guard let data = data else { return }
print(String(data: data, encoding: .utf8)!)
}
task.resume()
Rust
Rust is "a multi-paradigm systems programming language focused on safety, especially safe concurrency." - Wikipedia. Similar to C++.
Rust does not expose an http client?. You have to use hyper or reqwest. Does anyone know if its possible with just Rust?
Powershell (Windows) HTTP GET
Invoke-WebRequest "https://swapi.co/api/people/1/"
Shell (Bash etc) HTTP GET
curl "https://swapi.co/api/people/1/"
# or
curl -X GET -H "Accept: application/json" "https://swapi.co/api/people/1/"