Integrating the API with Popular Programming Languages
Eric @ CodableAI
Last Update há 2 anos
The Document Summarization API is designed to be language-agnostic, allowing seamless integration across various programming environments. This guide provides code examples and best practices for integrating the API using popular programming languages like Python, JavaScript, Java, and C#.
ContentsPython Integration
Utilizing Python's requests library for making API calls.
Prerequisites:
- Python 3.x installed.
- requests library (pip install requests).
Sample Python Code Snippet:
pythonCopy codeimport requests def summarize_text(text, format='paragraph', model='standard', tone='neutral', summary_length='standard', target_language=None): url = "https://api.yourdomain.com/document/summarize" headers = { "Content-Type": "application/json", "Ocp-Apim-Subscription-Key": "YOUR_SUBSCRIPTION_KEY" } payload = { "text": text, "format": format, "model": model, "customization": { "tone": tone, "summary_length": summary_length } } if target_language: payload["target_language"] = target_language response = requests.post(url, headers=headers, json=payload) if response.status_code == 200: data = response.json() if data["success"]: return data["summary"] else: print("Summarization failed.") else: print(f"Error: {response.status_code} - {response.text}") # Example Usage text_to_summarize = "Artificial Intelligence is transforming the world by enhancing various industries..." summary = summarize_text(text_to_summarize, format='bullet_points', tone='formal', target_language='es') print("Summary:", summary)
JavaScript Integration
Using JavaScript's Fetch API for making HTTP requests.
Sample JavaScript Code Snippet:
javascriptCopy codeasync function summarizeText(text, format = 'paragraph', model = 'standard', tone = 'neutral', summaryLength = 'standard', targetLanguage = null) { const url = "https://api.yourdomain.com/document/summarize"; const headers = { "Content-Type": "application/json", "Ocp-Apim-Subscription-Key": "YOUR_SUBSCRIPTION_KEY" }; const payload = { text: text, format: format, model: model, customization: { tone: tone, summary_length: summaryLength } }; if (targetLanguage) { payload.target_language = targetLanguage; } try { const response = await fetch(url, { method: 'POST', headers: headers, body: JSON.stringify(payload) }); const data = await response.json(); if (response.status === 200 && data.success) { return data.summary; } else { console.error("Summarization failed:", data.error); } } catch (error) { console.error("Error:", error); } } // Example Usage const textToSummarize = "Artificial Intelligence is transforming the world by enhancing various industries..."; summarizeText(textToSummarize, 'bullet_points', 'standard', 'formal', 'standard', 'es') .then(summary => console.log("Summary:", summary));
Java Integration
Leveraging Java's HttpURLConnection for making API calls.
Prerequisites:
- Java Development Kit (JDK) installed.
- JSON parsing library like org.json or Gson.
Sample Java Code Snippet:
javaCopy codeimport java.io.*; import java.net.HttpURLConnection; import java.net.URL; import org.json.JSONObject; public class DocumentSummarization { public static String summarizeText(String text, String format, String model, String tone, String summaryLength, String targetLanguage) { try { URL url = new URL("https://api.yourdomain.com/document/summarize"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("POST"); conn.setRequestProperty("Content-Type", "application/json"); conn.setRequestProperty("Ocp-Apim-Subscription-Key", "YOUR_SUBSCRIPTION_KEY"); conn.setDoOutput(true); JSONObject payload = new JSONObject(); payload.put("text", text); payload.put("format", format); payload.put("model", model); JSONObject customization = new JSONObject(); customization.put("tone", tone); customization.put("summary_length", summaryLength); payload.put("customization", customization); if (targetLanguage != null && !targetLanguage.isEmpty()) { payload.put("target_language", targetLanguage); } OutputStream os = conn.getOutputStream(); byte[] input = payload.toString().getBytes("utf-8"); os.write(input, 0, input.length); int responseCode = conn.getResponseCode(); BufferedReader br; if (responseCode == HttpURLConnection.HTTP_OK) { br = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8")); } else { br = new BufferedReader(new InputStreamReader(conn.getErrorStream(), "utf-8")); } StringBuilder response = new StringBuilder(); String responseLine; while ((responseLine = br.readLine()) != null) { response.append(responseLine.trim()); } JSONObject responseJson = new JSONObject(response.toString()); if (responseCode == HttpURLConnection.HTTP_OK && responseJson.getBoolean("success")) { return responseJson.getString("summary"); } else { System.out.println("Summarization failed: " + responseJson.getString("error")); } } catch (Exception e) { e.printStackTrace(); } return null; } // Example Usage public static void main(String[] args) { String textToSummarize = "Artificial Intelligence is transforming the world by enhancing various industries..."; String summary = summarizeText(textToSummarize, "bullet_points", "standard", "formal", "standard", "es"); System.out.println("Summary: " + summary); } }
C# Integration
Using C#'s HttpClient for making API calls.
Prerequisites:
- .NET Core or .NET Framework installed.
- Newtonsoft.Json package for JSON handling (Install-Package Newtonsoft.Json).
Sample C# Code Snippet:
csharpCopy codeusing System; using System.Net.Http; using System.Text; using System.Threading.Tasks; using Newtonsoft.Json.Linq; namespace DocumentSummarization { class Program { static async Task<string> SummarizeText(string text, string format = "paragraph", string model = "standard", string tone = "neutral", string summaryLength = "standard", string targetLanguage = null) { string url = "https://api.yourdomain.com/document/summarize"; using (HttpClient client = new HttpClient()) { client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", "YOUR_SUBSCRIPTION_KEY"); JObject payload = new JObject { { "text", text }, { "format", format }, { "model", model }, { "customization", new JObject { { "tone", tone }, { "summary_length", summaryLength } } } }; if (!string.IsNullOrEmpty(targetLanguage)) { payload.Add("target_language", targetLanguage); } StringContent content = new StringContent(payload.ToString(), Encoding.UTF8, "application/json"); HttpResponseMessage response = await client.PostAsync(url, content); string responseString = await response.Content.ReadAsStringAsync(); if (response.IsSuccessStatusCode) { JObject responseJson = JObject.Parse(responseString); if (responseJson["success"].Value<bool>()) { return responseJson["summary"].Value<string>(); } else { Console.WriteLine("Summarization failed: " + responseJson["error"].Value<string>()); } } else { Console.WriteLine($"Error: {response.StatusCode} - {responseString}"); } } return null; } // Example Usage static async Task Main(string[] args) { string textToSummarize = "Artificial Intelligence is transforming the world by enhancing various industries..."; string summary = await SummarizeText(textToSummarize, "bullet_points", "standard", "formal", "standard", "es"); Console.WriteLine("Summary: " + summary); } } }
Other Languages:
While Python, JavaScript, Java, and C# are commonly used, the API can be integrated with any language that supports HTTP requests. Ensure you handle JSON serialization/deserialization and manage headers appropriately in your chosen language.
Tips for Efficient Integration
Reusable HTTP Clients:
In languages like C# and Java, reuse HTTP client instances to optimize resource usage and performance.
Asynchronous Requests:
Implement asynchronous API calls to prevent blocking your application's main thread, enhancing responsiveness.
Error Handling:
Incorporate robust error handling mechanisms to manage API errors and unexpected responses gracefully.
Configuration Management:
Store sensitive information like subscription keys in environment variables or secure configuration files, avoiding hardcoding them in your source code.
Testing:
Use tools like Postman to test your API requests before implementing them in your codebase, ensuring correctness and reliability.
With integration examples across multiple programming languages, move forward to "Best Practices for Optimizing API Usage" to maximize the efficiency and effectiveness of your API interactions.
