api enable for users

This commit is contained in:
Ronaldson Bellande 2024-03-04 19:27:28 -05:00
parent ad1bc50d72
commit b6fe4dc092
2 changed files with 431 additions and 192 deletions

View File

@ -1,7 +1,10 @@
# 📦 Bellande Step # 📦 Bellande Step
# Check Out Research Organization for opensource/semi-opensource API
- https://robotics-sensors.github.io/
# API in api_docs # API in api_docs
- Temporarily Disabled - Temporarily Enabled
### ✔️ confirmed versions ### ✔️ confirmed versions
- `The step function efficiently computes the next step towards a target node within a specified distance limit.` - `The step function efficiently computes the next step towards a target node within a specified distance limit.`

View File

@ -6,119 +6,283 @@
import requests import requests
# Input variables # Input variables
x1 = 1 x1 = 0
y1 = 1 y1 = 0
x2 = 5 x2 = 5
y2 = 5 y2 = 5
limit = 50 limit = 3
# JSON payload
payload = {
"node0": {"x": x1, "y": y1},
"node1": {"x": x2, "y": y2}
}
# Headers
headers = {
'accept': 'application/json',
'Content-Type': 'application/json'
}
# Make POST request # Make POST request
response = requests.post('https://bellanderoboticssensorsresearchinnovationcenterapi-7xm5pkao.b4a.run/Bellande_Step/bellande_step_2d', json={"node0": {"x": x1, "y": y1}, "node1": {"x": x2, "y": y2}, "limit": limit}) try:
data = response.json() response = requests.post(
next_step = data.get('next_step') 'https://bellanderoboticssensorsresearchinnovationcenterapi-7xm5pkao.b4a.run/Bellande_Step/bellande_step_2d?limit=' + str(limit),
print(next_step) json=payload,
headers=headers
)
response.raise_for_status() # Raise an error for unsuccessful responses
data = response.json()
print("Next Step:", data['next_step'])
except requests.exceptions.RequestException as e:
print("Error:", e)
```
## C Example
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <curl/curl.h>
#include <jansson.h>
// Struct to hold response data
struct MemoryStruct {
char *memory;
size_t size;
};
// Callback function to write response data
static size_t WriteMemoryCallback(void *contents, size_t size, size_t nmemb, void *userp) {
size_t realsize = size * nmemb;
struct MemoryStruct *mem = (struct MemoryStruct *)userp;
mem->memory = realloc(mem->memory, mem->size + realsize + 1);
if (mem->memory == NULL) {
printf("Error: realloc failed\n");
return 0;
}
memcpy(&(mem->memory[mem->size]), contents, realsize);
mem->size += realsize;
mem->memory[mem->size] = 0;
return realsize;
}
int main() {
// Input variables
int x1 = 0;
int y1 = 0;
int x2 = 5;
int y2 = 5;
int limit = 3;
CURL *curl;
CURLcode res;
// Initialize libcurl
curl_global_init(CURL_GLOBAL_ALL);
// Create libcurl handle
curl = curl_easy_init();
if (curl) {
// Construct JSON payload
json_t *root = json_object();
json_object_set_new(root, "node0", json_pack("{s:i, s:i}", "x", x1, "y", y1));
json_object_set_new(root, "node1", json_pack("{s:i, s:i}", "x", x2, "y", y2));
char *payload = json_dumps(root, JSON_COMPACT);
json_decref(root);
// Construct URL with query parameter
char *url;
asprintf(&url, "https://bellanderoboticssensorsresearchinnovationcenterapi-7xm5pkao.b4a.run/Bellande_Step/bellande_step_2d?limit=%d", limit);
// Set libcurl options
curl_easy_setopt(curl, CURLOPT_URL, url);
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, payload);
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteMemoryCallback);
// Response data
struct MemoryStruct chunk;
chunk.memory = malloc(1);
chunk.size = 0;
curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void *)&chunk);
// Perform the request
res = curl_easy_perform(curl);
if (res != CURLE_OK) {
fprintf(stderr, "curl_easy_perform() failed: %s\n", curl_easy_strerror(res));
} else {
// Parse JSON response
json_error_t error;
json_t *root = json_loads(chunk.memory, 0, &error);
if (!root) {
fprintf(stderr, "Error parsing JSON: %s\n", error.text);
} else {
json_t *next_step = json_object_get(root, "next_step");
double x, y;
json_unpack(next_step, "{s:f, s:f}", "x", &x, "y", &y);
printf("Next Step: (%f, %f)\n", x, y);
json_decref(root);
}
}
// Cleanup
free(chunk.memory);
free(payload);
free(url);
curl_easy_cleanup(curl);
}
// Cleanup libcurl
curl_global_cleanup();
return 0;
}
``` ```
## C++ Example ## C++ Example
```c++ ```c++
#include <iostream> #include <iostream>
#include <cpprest/http_client.h> #include <string>
#include <cpprest/json.h> #include <curl/curl.h>
#include <nlohmann/json.hpp>
using namespace web; using json = nlohmann::json;
using namespace web::http;
using namespace web::http::client; // Struct to hold response data
struct MemoryStruct {
char *memory;
size_t size;
};
// Callback function to write response data
static size_t WriteMemoryCallback(void *contents, size_t size, size_t nmemb, void *userp) {
size_t realsize = size * nmemb;
struct MemoryStruct *mem = (struct MemoryStruct *)userp;
mem->memory = (char *)realloc(mem->memory, mem->size + realsize + 1);
if (mem->memory == NULL) {
std::cerr << "Error: realloc failed" << std::endl;
return 0;
}
memcpy(&(mem->memory[mem->size]), contents, realsize);
mem->size += realsize;
mem->memory[mem->size] = 0;
return realsize;
}
int main() { int main() {
// Input variables // Input variables
int x1 = 1; int x1 = 0;
int y1 = 1; int y1 = 0;
int x2 = 5; int x2 = 5;
int y2 = 5; int y2 = 5;
int limit = 50; int limit = 3;
// Create JSON objects CURL *curl;
json::value node0; CURLcode res;
node0[U("x")] = json::value::number(x1);
node0[U("y")] = json::value::number(y1);
json::value node1;
node1[U("x")] = json::value::number(x2);
node1[U("y")] = json::value::number(y2);
// Create JSON object for request body // Initialize libcurl
json::value request_body; curl_global_init(CURL_GLOBAL_ALL);
request_body[U("node0")] = node0;
request_body[U("node1")] = node1;
request_body[U("limit")] = json::value::number(limit);
// Make POST request // Create libcurl handle
http_client client(U("https://bellanderoboticssensorsresearchinnovationcenterapi-7xm5pkao.b4a.run/Bellande_Step/bellande_step_2d")); curl = curl_easy_init();
http_response response = client.request(methods::POST, U("/step"), request_body.serialize(), U("application/json")).get(); if (curl) {
// Construct JSON payload
// Parse response std::string payload = "{\"node0\":{\"x\":" + std::to_string(x1) + ",\"y\":" + std::to_string(y1) + "},\"node1\":{\"x\":" + std::to_string(x2) + ",\"y\":" + std::to_string(y2) + "}}";
if (response.status_code() == status_codes::OK) {
json::value response_body = response.extract_json().get(); // Construct URL with query parameter
json::value next_step = response_body[U("next_step")]; std::string url = "https://bellanderoboticssensorsresearchinnovationcenterapi-7xm5pkao.b4a.run/Bellande_Step/bellande_step_2d?limit=" + std::to_string(limit);
std::wcout << next_step.serialize() << std::endl;
} else { // Response data
std::cerr << "Error: " << response.status_code() << std::endl; struct MemoryStruct chunk;
chunk.memory = (char *)malloc(1);
chunk.size = 0;
// Set libcurl options
curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, payload.c_str());
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteMemoryCallback);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void *)&chunk);
// Perform the request
res = curl_easy_perform(curl);
if (res != CURLE_OK) {
std::cerr << "curl_easy_perform() failed: " << curl_easy_strerror(res) << std::endl;
} else {
// Parse JSON response
json data = json::parse(chunk.memory);
std::cout << "Next Step: (" << data["next_step"]["x"] << ", " << data["next_step"]["y"] << ")" << std::endl;
}
// Cleanup
free(chunk.memory);
curl_easy_cleanup(curl);
} }
// Cleanup libcurl
curl_global_cleanup();
return 0; return 0;
} }
``` ```
## Java Example ## Java Example
```java ```java
import java.net.HttpURLConnection; import org.json.JSONObject;
import java.net.URL; import java.net.URI;
import java.io.OutputStream; import java.net.http.HttpClient;
import java.io.BufferedReader; import java.net.http.HttpRequest;
import java.io.InputStreamReader; import java.net.http.HttpResponse;
public class Main { public class Main {
public static void main(String[] args) { public static void main(String[] args) {
// Input variables
int x1 = 0;
int y1 = 0;
int x2 = 5;
int y2 = 5;
int limit = 3;
// JSON payload
JSONObject payload = new JSONObject()
.put("node0", new JSONObject()
.put("x", x1)
.put("y", y1))
.put("node1", new JSONObject()
.put("x", x2)
.put("y", y2));
// Make POST request
try { try {
// Input variables HttpClient client = HttpClient.newHttpClient();
int x1 = 1; HttpRequest request = HttpRequest.newBuilder()
int y1 = 1; .uri(URI.create("https://bellanderoboticssensorsresearchinnovationcenterapi-7xm5pkao.b4a.run/Bellande_Step/bellande_step_2d?limit=" + limit))
int x2 = 5; .header("Content-Type", "application/json")
int y2 = 5; .header("Accept", "application/json")
int limit = 50; .POST(HttpRequest.BodyPublishers.ofString(payload.toString()))
.build();
// Create JSON objects HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
String node0 = "{\"x\": " + x1 + ", \"y\": " + y1 + "}";
String node1 = "{\"x\": " + x2 + ", \"y\": " + y2 + "}";
// Create request body if (response.statusCode() == 200) {
String requestBody = "{\"node0\": " + node0 + ", \"node1\": " + node1 + ", \"limit\": " + limit + "}"; JSONObject data = new JSONObject(response.body());
JSONObject nextStep = data.getJSONObject("next_step");
// Make POST request System.out.println("Next Step: (" + nextStep.getDouble("x") + ", " + nextStep.getDouble("y") + ")");
URL url = new URL("https://bellanderoboticssensorsresearchinnovationcenterapi-7xm5pkao.b4a.run/Bellande_Step/bellande_step_2d"); } else {
HttpURLConnection connection = (HttpURLConnection) url.openConnection(); System.out.println("Error: " + response.body());
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/json");
connection.setDoOutput(true);
try (OutputStream outputStream = connection.getOutputStream()) {
byte[] input = requestBody.getBytes("utf-8");
outputStream.write(input, 0, input.length);
}
try (BufferedReader responseReader = new BufferedReader(new InputStreamReader(connection.getInputStream()))) {
StringBuilder response = new StringBuilder();
String responseLine;
while ((responseLine = responseReader.readLine()) != null) {
response.append(responseLine.trim());
}
System.out.println(response.toString());
} }
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); System.out.println("Error: " + e.getMessage());
} }
} }
} }
@ -128,59 +292,90 @@ public class Main {
```javascript ```javascript
// Example using fetch API const fetch = require('node-fetch');
let x1 = 1;
let y1 = 1;
let x2 = 5;
let y2 = 5;
let limit = 50;
fetch('https://bellanderoboticssensorsresearchinnovationcenterapi-7xm5pkao.b4a.run/Bellande_Step/bellande_step_2d', { // Input variables
method: 'POST', const x1 = 0;
headers: { const y1 = 0;
'Content-Type': 'application/json' const x2 = 5;
}, const y2 = 5;
body: JSON.stringify({ const limit = 3;
// JSON payload
const payload = JSON.stringify({
node0: { x: x1, y: y1 }, node0: { x: x1, y: y1 },
node1: { x: x2, y: y2 }, node1: { x: x2, y: y2 }
limit: limit });
})
}) // Request parameters
.then(response => response.json()) const requestOptions = {
.then(data => console.log(data.next_step)) method: 'POST',
.catch(error => console.error('Error:', error)); headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: payload
};
// Make POST request
fetch(`https://bellanderoboticssensorsresearchinnovationcenterapi-7xm5pkao.b4a.run/Bellande_Step/bellande_step_2d?limit=${limit}`, requestOptions)
.then(response => {
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
return response.json();
})
.then(data => {
console.log("Next Step:", data.next_step);
})
.catch(error => {
console.error("Error:", error);
});
``` ```
## Rust Example ## Rust Example
```rust ```rust
use reqwest::blocking::Client;
use serde_json::json; use serde_json::json;
fn main() -> Result<(), Box<dyn std::error::Error>> { #[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
// Input variables // Input variables
let x1 = 1; let x1 = 0;
let y1 = 1; let y1 = 0;
let x2 = 5; let x2 = 5;
let y2 = 5; let y2 = 5;
let limit = 50; let limit = 3;
// Create JSON objects // JSON payload
let node0 = json!({"x": x1, "y": y1}); let payload = json!({
let node1 = json!({"x": x2, "y": y2}); "node0": {"x": x1, "y": y1},
"node1": {"x": x2, "y": y2}
// Create JSON object for request body });
let request_body = json!({"node0": node0, "node1": node1, "limit": limit});
// Make POST request // Make POST request
let client = Client::new(); let client = reqwest::Client::new();
let response = client.post("https://bellanderoboticssensorsresearchinnovationcenterapi-7xm5pkao.b4a.run/Bellande_Step/bellande_step_2d") let response = client
.json(&request_body) .post("https://bellanderoboticssensorsresearchinnovationcenterapi-7xm5pkao.b4a.run/Bellande_Step/bellande_step_2d")
.send()?; .query(&[("limit", &limit.to_string())])
.json(&payload)
let data: serde_json::Value = response.json()?; .send()
println!("{}", data["next_step"]); .await?;
// Check if response is successful
if response.status().is_success() {
// Parse response JSON
let data: serde_json::Value = response.json().await?;
// Print next_step
if let Some(next_step) = data.get("next_step") {
println!("Next Step: {}", next_step);
} else {
println!("Next Step not found in response.");
}
} else {
println!("Error: {}", response.status());
}
Ok(()) Ok(())
} }
@ -201,91 +396,147 @@ import (
func main() { func main() {
// Input variables // Input variables
x1 := 1 x1 := 0
y1 := 1 y1 := 0
x2 := 5 x2 := 5
y2 := 5 y2 := 5
limit := 50 limit := 3
// Create request body // JSON payload
node0 := map[string]int{"x": x1, "y": y1} payload := map[string]interface{}{
node1 := map[string]int{"x": x2, "y": y2} "node0": map[string]int{"x": x1, "y": y1},
requestBody := map[string]interface{}{"node0": node0, "node1": node1, "limit": limit} "node1": map[string]int{"x": x2, "y": y2},
}
// Marshal JSON // Convert payload to JSON
jsonBody, err := json.Marshal(requestBody) payloadBytes, err := json.Marshal(payload)
if err != nil { if err != nil {
fmt.Println("Error marshaling JSON:", err) fmt.Println("Error marshaling JSON:", err)
return return
} }
// Make POST request // Make POST request
resp, err := http.Post("https://bellanderoboticssensorsresearchinnovationcenterapi-7xm5pkao.b4a.run/Bellande_Step/bellande_step_2d", "application/json", bytes.NewBuffer(jsonBody)) url := fmt.Sprintf("https://bellanderoboticssensorsresearchinnovationcenterapi-7xm5pkao.b4a.run/Bellande_Step/bellande_step_2d?limit=%d", limit)
req, err := http.NewRequest("POST", url, bytes.NewBuffer(payloadBytes))
if err != nil {
fmt.Println("Error creating request:", err)
return
}
// Set headers
req.Header.Set("Accept", "application/json")
req.Header.Set("Content-Type", "application/json")
// Create HTTP client and send request
client := &http.Client{}
resp, err := client.Do(req)
if err != nil { if err != nil {
fmt.Println("Error making request:", err) fmt.Println("Error making request:", err)
return return
} }
defer resp.Body.Close() defer resp.Body.Close()
// Read response body // Check if response is successful
var response map[string]interface{} if resp.StatusCode != http.StatusOK {
err = json.NewDecoder(resp.Body).Decode(&response) fmt.Println("Error:", resp.Status)
if err != nil { return
fmt.Println("Error decoding response:", err) }
// Decode response JSON
var data map[string]interface{}
if err := json.NewDecoder(resp.Body).Decode(&data); err != nil {
fmt.Println("Error decoding JSON:", err)
return return
} }
// Print next_step // Print next_step
fmt.Println(response["next_step"]) nextStep, ok := data["next_step"].(string)
if !ok {
fmt.Println("Next Step not found in response.")
return
}
fmt.Println("Next Step:", nextStep)
} }
``` ```
## Swift Example ## Swift Example
```swift ```swift
import Foundation import Foundation
// Define input variables // Input variables
let x1 = 1 let x1 = 0
let y1 = 1 let y1 = 0
let x2 = 5 let x2 = 5
let y2 = 5 let y2 = 5
let limit = 50 let limit = 3
// Create JSON request body // JSON payload
let requestBody: [String: Any] = [ let payload = [
"node0": ["x": x1, "y": y1], "node0": ["x": x1, "y": y1],
"node1": ["x": x2, "y": y2], "node1": ["x": x2, "y": y2]
"limit": limit
] ]
// Convert request body to Data // Convert payload to Data
let jsonData = try! JSONSerialization.data(withJSONObject: requestBody) guard let payloadData = try? JSONSerialization.data(withJSONObject: payload) else {
print("Error converting payload to Data.")
exit(1)
}
// Create HTTP request // Request URL
var request = URLRequest(url: URL(string: "https://bellanderoboticssensorsresearchinnovationcenterapi-7xm5pkao.b4a.run/Bellande_Step/bellande_step_2d")!) let urlString = "https://bellanderoboticssensorsresearchinnovationcenterapi-7xm5pkao.b4a.run/Bellande_Step/bellande_step_2d?limit=\(limit)"
guard let url = URL(string: urlString) else {
print("Error creating URL.")
exit(1)
}
// Create URLRequest
var request = URLRequest(url: url)
request.httpMethod = "POST" request.httpMethod = "POST"
request.setValue("application/json", forHTTPHeaderField: "Content-Type") request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.httpBody = jsonData request.setValue("application/json", forHTTPHeaderField: "Accept")
request.httpBody = payloadData
// Send HTTP request // Perform the request
let task = URLSession.shared.dataTask(with: request) { data, response, error in let task = URLSession.shared.dataTask(with: request) { data, response, error in
guard let data = data, error == nil else { // Check for errors
print("Error: \(error?.localizedDescription ?? "Unknown error")") if let error = error {
print("Error:", error)
return return
} }
// Parse response JSON // Check for response
guard let httpResponse = response as? HTTPURLResponse else {
print("Error: No HTTP response")
return
}
// Check for successful response
guard (200...299).contains(httpResponse.statusCode) else {
print("Error: HTTP status code \(httpResponse.statusCode)")
return
}
// Check if there is data
guard let responseData = data else {
print("Error: No response data")
return
}
// Parse JSON response
do { do {
if let json = try JSONSerialization.jsonObject(with: data) as? [String: Any] { if let jsonResponse = try JSONSerialization.jsonObject(with: responseData, options: []) as? [String: Any],
if let nextStep = json["next_step"] { let nextStep = jsonResponse["next_step"] as? String {
print(nextStep) print("Next Step:", nextStep)
} } else {
print("Error: Couldn't find next_step in JSON response")
} }
} catch { } catch {
print("Error decoding response: \(error.localizedDescription)") print("Error parsing JSON response:", error)
} }
} }
task.resume() task.resume()
``` ```
@ -295,64 +546,49 @@ task.resume()
using System; using System;
using System.Net.Http; using System.Net.Http;
using System.Text.Json;
using System.Threading.Tasks; using System.Threading.Tasks;
using Newtonsoft.Json;
class Program class Program
{ {
static async Task Main(string[] args) static async Task Main(string[] args)
{ {
// Input variables // Input variables
int x1 = 1; int x1 = 0;
int y1 = 1; int y1 = 0;
int x2 = 5; int x2 = 5;
int y2 = 5; int y2 = 5;
int limit = 50; int limit = 3;
// Create JSON request body // JSON payload
var requestBody = new var payload = new
{ {
node0 = new { x = x1, y = y1 }, node0 = new { x = x1, y = y1 },
node1 = new { x = x2, y = y2 }, node1 = new { x = x2, y = y2 }
limit = limit
}; };
// Convert request body to JSON string // Convert payload to JSON
var jsonBody = JsonConvert.SerializeObject(requestBody); var payloadJson = JsonSerializer.Serialize(payload);
var content = new StringContent(payloadJson, System.Text.Encoding.UTF8, "application/json");
// Create HttpClient // Make POST request
using (var client = new HttpClient()) using var client = new HttpClient();
var url = $"https://bellanderoboticssensorsresearchinnovationcenterapi-7xm5pkao.b4a.run/Bellande_Step/bellande_step_2d?limit={limit}";
try
{ {
// Set base address of API var response = await client.PostAsync(url, content);
client.BaseAddress = new Uri("https://bellanderoboticssensorsresearchinnovationcenterapi-7xm5pkao.b4a.run/Bellande_Step/bellande_step_2d"); response.EnsureSuccessStatusCode(); // Throws exception for unsuccessful responses
// Set headers // Parse JSON response
client.DefaultRequestHeaders.Accept.Clear(); var responseContent = await response.Content.ReadAsStringAsync();
client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json")); var responseData = JsonSerializer.Deserialize<dynamic>(responseContent);
// Make POST request // Print next_step
var response = await client.PostAsync("", new StringContent(jsonBody, System.Text.Encoding.UTF8, "application/json")); Console.WriteLine("Next Step: " + responseData.next_step);
}
// Check if request was successful catch (HttpRequestException e)
if (response.IsSuccessStatusCode) {
{ Console.WriteLine("Error: " + e.Message);
// Read response content
var responseContent = await response.Content.ReadAsStringAsync();
// Deserialize JSON response
dynamic responseData = JsonConvert.DeserializeObject(responseContent);
// Get next_step from response
var nextStep = responseData.next_step;
// Print next_step
Console.WriteLine(nextStep);
}
else
{
// Print error message
Console.WriteLine($"Error: {response.StatusCode}");
}
} }
} }
} }