Skip to content

Instantly share code, notes, and snippets.

@Naramsim
Last active February 1, 2024 19:27
Show Gist options
  • Save Naramsim/53957e11015d4a7f2c890c8cbdea45a9 to your computer and use it in GitHub Desktop.
Save Naramsim/53957e11015d4a7f2c890c8cbdea45a9 to your computer and use it in GitHub Desktop.

Requests examples

http://pokeapi.api-docs.io/v2.0

cURL

curl --request GET --url http://pokeapi.co/api/v2/pokemon/bulbasaur/

Wget

wget --quiet \
    --method GET \
    --output-document \
    - http://pokeapi.co/api/v2/pokemon/bulbasaur/

Go

package main

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

func main() {

    url := "http://pokeapi.co/api/v2/pokemon/bulbasaur/"

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

    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("http://pokeapi.co/api/v2/pokemon/bulbasaur/")
    .asString();

Java OkHttp

OkHttpClient client = new OkHttpClient();

Request request = new Request.Builder()
    .url("http://pokeapi.co/api/v2/pokemon/bulbasaur/")
    .get()
    .build();

Response response = client.newCall(request).execute();

Javascript

var data = null;

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

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

xhr.open("GET", "http://pokeapi.co/api/v2/pokemon/bulbasaur/");

xhr.send(data);

jQuery

var settings = {
    "async": true,
    "crossDomain": true,
    "url": "http://pokeapi.co/api/v2/pokemon/bulbasaur/",
    "method": "GET",
    "headers": {}
}

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

Node

var http = require("http");

var options = {
    "method": "GET",
    "hostname": "pokeapi.co",
    "port": null,
    "path": "/api/v2/pokemon/bulbasaur/",
    "headers": {}
};

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(JSON.parse(body.toString()));
    });
});

req.end();

Request.js

var request = require("request");

var options = { method: 'GET',
    url: 'http://pokeapi.co/api/v2/pokemon/bulbasaur/' };

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

    console.log(JSON.parse(body));
});

Unirest.js

var unirest = require("unirest");

var req = unirest("GET", "http://pokeapi.co/api/v2/pokemon/bulbasaur/");


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

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

Obj-C

#import <Foundation/Foundation.h>

NSData *postData = [[NSData alloc] initWithData:[@"" dataUsingEncoding:NSUTF8StringEncoding]];

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://pokeapi.co/api/v2/pokemon/bulbasaur/"]
                                                                                                             cachePolicy:NSURLRequestUseProtocolCachePolicy
                                                                                                     timeoutInterval:10.0];
[request setHTTPMethod:@"GET"];
[request setHTTPBody:postData];

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];

PHP

<?php

$curl = curl_init();

curl_setopt_array($curl, array(
    CURLOPT_URL => "http://pokeapi.co/api/v2/pokemon/bulbasaur/",
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_ENCODING => "",
    CURLOPT_MAXREDIRS => 10,
    CURLOPT_TIMEOUT => 30,
    CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
    CURLOPT_CUSTOMREQUEST => "GET",
    CURLOPT_POSTFIELDS => "",
));

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

curl_close($curl);

if ($err) {
    echo "cURL Error #:" . $err;
} else {
    $json = json_decode(response, true);
}
<?php

$request = new HttpRequest();
$request->setUrl('http://pokeapi.co/api/v2/pokemon/bulbasaur/');
$request->setMethod(HTTP_METH_GET);

try {
  $response = $request->send();
  $json = json_decode($response->getBody(), true);
} catch (HttpException $ex) {
  echo $ex;
}

Python 3

import http.client
import json

conn = http.client.HTTPConnection("pokeapi.co")

payload = ""

conn.request("GET", "/api/v2/pokemon/bulbasaur/", payload)

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

obj = json.loads(data.decode("utf-8"))
import requests

url = "http://pokeapi.co/api/v2/pokemon/bulbasaur/"

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

data = response.json()

Ruby

require 'uri'
require 'net/http'

url = URI("http://pokeapi.co/api/v2/pokemon/bulbasaur/")

http = Net::HTTP.new(url.host, url.port)

request = Net::HTTP::Get.new(url)

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

Swift

import Foundation

let postData = NSData(data: "".dataUsingEncoding(NSUTF8StringEncoding)!)

var request = NSMutableURLRequest(URL: NSURL(string: "http://pokeapi.co/api/v2/pokemon/bulbasaur/")!,
                                                                                cachePolicy: .UseProtocolCachePolicy,
                                                                        timeoutInterval: 10.0)
request.HTTPMethod = "GET"
request.HTTPBody = postData

let session = NSURLSession.sharedSession()
let dataTask = session.dataTaskWithRequest(request, completionHandler: { (data, response, error) -> Void in
    if (error != nil) {
        println(error)
    } else {
        let httpResponse = response as? NSHTTPURLResponse
        println(httpResponse)
    }
})

dataTask.resume()

C#

var client = new RestClient("http://pokeapi.co/api/v2/pokemon/bulbasaur/");
var request = new RestRequest(Method.GET);
IRestResponse response = client.Execute(request);

C# with Newtonsoft json and Restsharp

var client = new RestClient("http://pokeapi.co/api/v2/pokemon/bulbasaur/");
var request = new RestRequest(Method.GET);
IRestResponse response = client.Execute(request);
var content = response.Content;
dynamic pokemon = JsonConvert.DeserializeObject(content);
string name = pokemon.name;
string id = pokemon.id;

C

CURL *hnd = curl_easy_init();

curl_easy_setopt(hnd, CURLOPT_CUSTOMREQUEST, "GET");
curl_easy_setopt(hnd, CURLOPT_URL, "http://pokeapi.co/api/v2/pokemon/bulbasaur/");

CURLcode ret = curl_easy_perform(hnd);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment