Skip to content

Instantly share code, notes, and snippets.

@robert52
Last active December 25, 2015 19:09
Show Gist options
  • Save robert52/7025696 to your computer and use it in GitHub Desktop.
Save robert52/7025696 to your computer and use it in GitHub Desktop.
A small c# wrapper for BeGlobal API requests
using System;
using System.IO;
using System.Net;
using System.Text;
public enum HttpVerb
{
GET,
POST,
PUT,
DELETE
}
public class BeGlobalClient {
public string Token { get; set; }
private readonly string ContentType = "application/json";
public BeGlobalClient(string token) {
Token = token; //your BeGlobal API key instead of `BeGlobalAPIKey`
}
public string MakeRequest(string endpoint, HttpVerb method, string data) {
var request = (HttpWebRequest)WebRequest.Create(endpoint);
request.Method = method.ToString();
request.ContentLength = 0;
request.ContentType = ContentType;
request.Headers.Add("Authorization", "BeGlobal apiKey=" + Token);
if (!string.IsNullOrEmpty(data) && method == HttpVerb.POST) {
var encoding = new UTF8Encoding();
var bytes = Encoding.GetEncoding("iso-8859-1").GetBytes(data);
request.ContentLength = bytes.Length;
using (var writeStream = request.GetRequestStream()) {
writeStream.Write(bytes, 0, bytes.Length);
}
}
using (var response = (HttpWebResponse)request.GetResponse()) {
var responseValue = string.Empty;
if (response.StatusCode != HttpStatusCode.OK) {
var message = String.Format("Request failed. Received HTTP {0}", response.StatusCode);
throw new ApplicationException(message);
}
// grab the response
using (var responseStream = response.GetResponseStream()) {
if (responseStream != null) {
using (var reader = new StreamReader(responseStream)) {
responseValue = reader.ReadToEnd();
}
}
}
return responseValue;
}
}
}
//Example of asking for a translation from the BeGlobal API
//see: https://www.beglobal.com/developers/api-documentation/ for more info
//define the endpoint
string endPoint = @"https://api.beglobal.com/translate";
//create a new client and set your BeGlobal API key
var client = new BeGlobalClient(token: "BeGlobalAPIKey");
//make a request
var json = client.MakeRequest(endpoint: endPoint,
method: HttpVerb.POST,
data: "{'text': 'text to be translated', 'from': 'eng', to: 'fra'}");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment