Skip to content

Instantly share code, notes, and snippets.

@sanjarcode
Last active September 3, 2023 14:14
Show Gist options
  • Save sanjarcode/c3e6c94d9d47ccaf86c7954c795bf7ae to your computer and use it in GitHub Desktop.
Save sanjarcode/c3e6c94d9d47ccaf86c7954c795bf7ae to your computer and use it in GitHub Desktop.
HTTP requests in variouslanguages/runtimes

HTTP Requests and responses in various languages

JavaScript

1. fetch API

// GET request
fetch('https://example.com/data')
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.error(error))
// POST request
fetch('https://example.com/data', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({
    name: 'John Doe',
    email: 'john.doe@example.com'
  })
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error(error))

2. axios

// GET request
const axios = require('axios');

axios.get('https://example.com/data')
  .then(response => console.log(response.data))
  .catch(error => console.error(error))
// POST request
const axios = require('axios');

axios.post('https://example.com/data', {
  name: 'John Doe',
  email: 'john.doe@example.com'
})
.then(response => console.log(response.data))
.catch(error => console.error(error))

3. axios + 'await-to-js'

const to = require('await-to-js').to;
const axios = require('axios');

async function fetchData() {
  const [error, response] = await to(axios.get('https://example.com/data'));
  if (error) {
    console.error(error);
    return;
  }
  console.log(response.data);
}

fetchData();
const to = require('await-to-js').to;
const axios = require('axios');

async function postData() {
  const [error, response] = await to(axios.post('https://example.com/data', {
    name: 'John Doe',
    email: 'john.doe@example.com'
  }));
  if (error) {
    console.error(error);
    return;
  }
  console.log(response.data);
}

postData();

Bash

cURL

# GET request
curl https://example.com/data
# POST request
curl -X POST -H 'Content-Type: application/json' -d '{"name": "John Doe", "email": "john.doe@example.com"}' https://example.com/data

Python

import requests

# GET request
response = requests.get('https://example.com/data')
if response.status_code == 200:
    data = response.json()
    print(data)
else:
    print(f'Request failed with status code {response.status_code}')
# POST request
response = requests.post('https://example.com/data', json={
    'name': 'John Doe',
    'email': 'john.doe@example.com'
})
if response.status_code == 200:
    data = response.json()
    print(data)
else:
    print(f'Request failed with status code {response.status_code}')

C++

simple (global std namespace)

#include <curl/curl.h>
#include <iostream>
#include <string>
#include <vector>

using namespace std;

// Callback function to handle the response data
size_t write_callback(const char* ptr, size_t size, size_t nmemb, string& userdata) {
    size_t num_bytes = size * nmemb;
    userdata.append(ptr, num_bytes);
    return num_bytes;
}

int main() {
    CURL* curl = curl_easy_init();
    if (curl) {
        CURLcode res;

        // GET request
        string url = "https://example.com/data";
        string response_data;
        curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
        curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_callback);
        curl_easy_setopt(curl, CURLOPT_WRITEDATA, &response_data);
        res = curl_easy_perform(curl);
        if (res != CURLE_OK) {
            cerr << "curl_easy_perform() failed: " << curl_easy_strerror(res) << endl;
        } else {
            cout << "GET response: " << response_data << endl;
        }

        // POST request
        url = "https://example.com/data";
        response_data.clear();
        vector<string> headers = { "Content-Type: application/json" };
        string post_data = "{\"name\": \"John Doe\", \"email\": \"john.doe@example.com\"}";
        curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
        curl_easy_setopt(curl, CURLOPT_POST, 1L);
        curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
        curl_easy_setopt(curl, CURLOPT_POSTFIELDS, post_data.c_str());
        curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_callback);
        curl_easy_setopt(curl, CURLOPT_WRITEDATA, &response_data);
        res = curl_easy_perform(curl);
        if (res != CURLE_OK) {
            cerr << "curl_easy_perform() failed: " << curl_easy_strerror(res) << endl;
        } else {
            cout << "POST response: " << response_data << endl;
        }

        curl_easy_cleanup(curl);
    }
    return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment