import os
import requests
response = requests.post(
f"https://api.aws.amazon.com/2016-11-15/functions/{os.environ['FUNCTION_NAME']}/invocations",
headers={
"x-amz-date": "20230101T000000Z",
"Authorization": os.environ["AWS_AUTH_HEADER"]
},
json={"payload": {"key": "value"}}
)
if response.status_code >= 400:
raise Exception(f"Request failed: {response.text}")
print(response.json())
import os
import httpx
with httpx.Client() as client:
response = client.post(
f"https://api.aws.amazon.com/2016-11-15/functions/{os.environ['FUNCTION_NAME']}/invocations",
headers={
"x-amz-date": "20230101T000000Z",
"Authorization": os.environ["AWS_AUTH_HEADER"]
},
json={"payload": {"key": "value"}}
)
if response.status_code >= 400:
raise Exception(f"Request failed: {response.text}")
print(response.json())
import fetch from 'node-fetch';
import process from 'process';
const response = await fetch(
`https://api.aws.amazon.com/2016-11-15/functions/${process.env.FUNCTION_NAME}/invocations`,
{
method: 'POST',
headers: {
'x-amz-date': '20230101T000000Z',
'Authorization': process.env.AWS_AUTH_HEADER
},
body: JSON.stringify({ payload: { key: 'value' } })
}
);
if (!response.ok) {
throw new Error(`Request failed: ${await response.text()}`);
}
console.log(await response.json());
import axios from 'axios';
import process from 'process';
const response = await axios.post(
`https://api.aws.amazon.com/2016-11-15/functions/${process.env.FUNCTION_NAME}/invocations`,
{ payload: { key: 'value' } },
{
headers: {
'x-amz-date': '20230101T000000Z',
'Authorization': process.env.AWS_AUTH_HEADER
}
}
);
if (response.status >= 400) {
throw new Error(`Request failed: ${response.statusText}`);
}
console.log(response.data);
package main
import (
"encoding/json"
"fmt"
"log"
"net/http"
"os"
)
func main() {
client := &http.Client{}
url := fmt.Sprintf("https://api.aws.amazon.com/2016-11-15/functions/%s/invocations", os.Getenv("FUNCTION_NAME"))
req, err := http.NewRequest("POST", url, nil)
if err != nil {
log.Fatal(err)
}
req.Header.Set("x-amz-date", "20230101T000000Z")
req.Header.Set("Authorization", os.Getenv("AWS_AUTH_HEADER"))
body := map[string]interface{}{
"payload": map[string]string{"key": "value"},
}
bodyBytes, _ := json.Marshal(body)
req.Body = http.NoBody
req.GetBody = func() (io.ReadCloser, error) {
return io.NopCloser(bytes.NewReader(bodyBytes)), nil
}
resp, err := client.Do(req)
if err != nil {
log.Fatal(err)
}
defer resp.Body.Close()
if resp.StatusCode >= 400 {
log.Fatalf("Request failed: %s", resp.Status)
}
var result map[string]interface{}
json.NewDecoder(resp.Body).Decode(&result)
fmt.Println(result)
}
<?php
$ch = curl_init();
$url = sprintf(
'https://api.aws.amazon.com/2016-11-15/functions/%s/invocations',
urlencode(getenv('FUNCTION_NAME'))
);
$body = json_encode(['payload' => ['key' => 'value']]);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $body);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'x-amz-date: 20230101T000000Z',
'Authorization: ' . getenv('AWS_AUTH_HEADER'),
'Content-Type: application/json'
]);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($httpCode >= 400) {
throw new Exception("Request failed: " . $response);
}
print_r(json_decode($response, true));
require 'net/http'
require 'json'
require 'uri'
uri = URI.parse("https://api.aws.amazon.com/2016-11-15/functions/#{ENV['FUNCTION_NAME']}/invocations")
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true
request = Net::HTTP::Post.new(uri.request_uri)
request['x-amz-date'] = '20230101T000000Z'
request['Authorization'] = ENV['AWS_AUTH_HEADER']
request.body = { payload: { key: 'value' } }.to_json
response = http.request(request)
if response.code.to_i >= 400
raise "Request failed: #{response.body}"
end
puts JSON.parse(response.body)
import Foundation
let url = URL(string: "https://api.aws.amazon.com/2016-11-15/functions/" + ProcessInfo.processInfo.environment["FUNCTION_NAME"]! + "/invocations")!
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.setValue("20230101T000000Z", forHTTPHeaderField: "x-amz-date")
request.setValue(ProcessInfo.processInfo.environment["AWS_AUTH_HEADER"]!, forHTTPHeaderField: "Authorization")
let body: [String: Any] = ["payload": ["key": "value"]]
request.httpBody = try JSONSerialization.data(withJSONObject: body)
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
let task = URLSession.shared.dataTask(with: request) { data, response, error in
if let error = error {
fatalError("Request failed: \(error)")
}
guard let httpResponse = response as? HTTPURLResponse, httpResponse.statusCode < 400 else {
fatalError("Request failed with status: \((response as? HTTPURLResponse)?.statusCode ?? 0)")
}
if let data = data {
let json = try JSONSerialization.jsonObject(with: data)
print(json)
}
}
task.resume()
RunLoop.main.run()
use std::env;
use reqwest::blocking::Client;
use serde_json::json;
fn main() -> Result<(), Box<dyn std::error::Error>> {
let client = Client::new();
let function_name = env::var("FUNCTION_NAME")?;
let auth_header = env::var("AWS_AUTH_HEADER")?;
let url = format!("https://api.aws.amazon.com/2016-11-15/functions/{}/invocations", function_name);
let body = json!({"payload": {"key": "value"}});
let response = client
.post(&url)
.header("x-amz-date", "20230101T000000Z")
.header("Authorization", auth_header)
.json(&body)
.send()?;
if !response.status().is_success() {
return Err(format!("Request failed: {}", response.text()?).into());
}
println!("{:?}", response.json::<serde_json::Value>()?);
Ok(())
}
using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text.Json;
using System.Threading.Tasks;
class Program
{
static async Task Main()
{
var client = new HttpClient();
var functionName = Environment.GetEnvironmentVariable("FUNCTION_NAME");
var authHeader = Environment.GetEnvironmentVariable("AWS_AUTH_HEADER");
var url = $"https://api.aws.amazon.com/2016-11-15/functions/{functionName}/invocations";
var body = new { payload = new { key = "value" } };
var request = new HttpRequestMessage(HttpMethod.Post, url)
{
Content = new StringContent(JsonSerializer.Serialize(body))
{
Headers = { ContentType = new MediaTypeHeaderValue("application/json") }
}
};
request.Headers.Add("x-amz-date", "20230101T000000Z");
request.Headers.Add("Authorization", authHeader);
var response = await client.SendAsync(request);
if (!response.IsSuccessStatusCode)
{
throw new Exception($"Request failed: {await response.Content.ReadAsStringAsync()}");
}
var result = await response.Content.ReadAsStringAsync();
Console.WriteLine(result);
}
}