using namespace System.Net
# Input bindings are passed in via param block.
param($Request, $TriggerMetadata)
# Write to the Azure Functions log stream.
Write-Host "PowerShell HTTP trigger function processed a request."
# Interact with query parameters
$name = $Request.Query.name
$body = "This HTTP triggered function executed successfully. Pass a name in the query string for a personalized response."
if ($name) {
$body = "Hello, $name. This HTTP triggered function executed successfully."
}
# Associate values to output bindings by calling 'Push-OutputBinding'.
Push-OutputBinding -Name Response -Value ([HttpResponseContext]@{
StatusCode = [HttpStatusCode]::OK
Body = $body
})
@app.route(route="httpget", methods=["GET"])
def http_get(req: func.HttpRequest) -> func.HttpResponse:
name = req.params.get("name", "World")
logging.info(f"Processing GET request. Name: {name}")
return func.HttpResponse(f"Hello, {name}!")
[Function("httppost")]
public IActionResult Run([HttpTrigger(AuthorizationLevel.Function, "post")] HttpRequest req,
[FromBody] Person person)
{
_logger.LogInformation($"C# HTTP POST trigger function processed a request for url {req.Body}");
if (string.IsNullOrEmpty(person.Name) | string.IsNullOrEmpty(person.Age.ToString()) | person.Age == 0)
{
_logger.LogInformation("C# HTTP POST trigger function processed a request with no name/age provided.");
return new BadRequestObjectResult("Please provide both name and age in the request body.");
}
var returnValue = $"Hello, {person.Name}! You are {person.Age} years old.";
_logger.LogInformation($"C# HTTP POST trigger function processed a request for {person.Name} who is {person.Age} years old.");
return new OkObjectResult(returnValue);
}
@FunctionName("httppost")
public HttpResponseMessage runPost(
@HttpTrigger(
name = "req",
methods = {HttpMethod.POST},
authLevel = AuthorizationLevel.FUNCTION)
HttpRequestMessage<Optional<String>> request,
final ExecutionContext context) {
context.getLogger().info("Java HTTP trigger processed a POST request.");
// Parse request body
String name;
Integer age;
try {
ObjectMapper mapper = new ObjectMapper();
JsonNode jsonNode = mapper.readTree(request.getBody().orElse("{}"));
name = Optional.ofNullable(jsonNode.get("name")).map(JsonNode::asText).orElse(null);
age = Optional.ofNullable(jsonNode.get("age")).map(JsonNode::asInt).orElse(null);
if (name == null || age == null) {
return request.createResponseBuilder(HttpStatus.BAD_REQUEST)
.body("Please provide both name and age in the request body.").build();
}
} catch (Exception e) {
context.getLogger().severe("Error parsing request body: " + e.getMessage());
return request.createResponseBuilder(HttpStatus.BAD_REQUEST)
.body("Error parsing request body").build();
}
const { app } = require('@azure/functions');
app.http('httppost', {
methods: ['POST'],
authLevel: 'function',
handler: async (request, context) => {
context.log(`Http function processed request for url "${request.url}"`);
try {
const person = await request.json();
const { name, age } = person;
if (!name || !age) {
return {
status: 400,
body: 'Please provide both name and age in the request body.'
};
}
return {
status: 200,
body: `Hello, ${name}! You are ${age} years old.`
};
} catch (error) {
return {
status: 400,
body: 'Invalid request body. Please provide a valid JSON object with name and age.'
};
}
}
});
import { app, HttpRequest, HttpResponseInit, InvocationContext } from "@azure/functions";
interface Person {
name: string;
age: number;
}
function isPerson(obj: any): obj is Person {
return typeof obj === 'object' && obj !== null &&
typeof obj.name === 'string' &&
typeof obj.age === 'number';
}
export async function httpPostBodyFunction(request: HttpRequest, context: InvocationContext): Promise<HttpResponseInit> {
context.log(`Http function processed request for url "${request.url}"`);
try {
const data: any = await request.json();
if (!isPerson(data)) {
return {
status: 400,
body: 'Please provide both name and age in the request body.'
};
}
return {
status: 200,
body: `Hello, ${data.name}! You are ${data.age} years old.`
};
} catch (error) {
return {
status: 400,
body: 'Invalid request body. Please provide a valid JSON object with name and age.'
};
}
};
app.http('httppost', {
methods: ['POST'],
authLevel: 'function',
handler: httpPostBodyFunction
});
using namespace System.Net
# Input bindings are passed in via param block.
param($Request, $TriggerMetadata)
# Write to the Azure Functions log stream.
Write-Host "PowerShell HTTP trigger function processed a request."
# Interact with the body of the request.
$name = $Request.Body.name
$age = $Request.Body.age
$status = [HttpStatusCode]::OK
$body = "This HTTP triggered function executed successfully. Pass a name in the request body for a personalized response."
if ( -not ($name -and $age)){
$body = "Please provide both 'name' and 'age' in the request body."
$status = [HttpStatusCode]::BadRequest
}
else {
<# Action when all if and elseif conditions are false #>
$body = "Hello, ${name}! You are ${age} years old."
}
# Associate values to output bindings by calling 'Push-OutputBinding'.
Push-OutputBinding -Name Response -Value ([HttpResponseContext]@{
StatusCode = $status
Body = $body
})
@app.route(route="httppost", methods=["POST"])
def http_post(req: func.HttpRequest) -> func.HttpResponse:
try:
req_body = req.get_json()
name = req_body.get('name')
age = req_body.get('age')
logging.info(f"Processing POST request. Name: {name}")
if name and isinstance(name, str) and age and isinstance(age, int):
return func.HttpResponse(f"Hello, {name}! You are {age} years old!")
else:
return func.HttpResponse(
"Please provide both 'name' and 'age' in the request body.",
status_code=400
)
except ValueError:
return func.HttpResponse(
"Invalid JSON in request body",
status_code=400
)