Creating HTTP Requests with Functions
One of the standout features of PhotonIQ Functions is its ability to execute functions in response to HTTP requests, empowering developers to build robust serverless web applications and APIs with ease.
PhotonIQ Functions allows you to create APIs that handle various HTTP methods, such as GET, POST, PUT, and DELETE, enabling the design and deployment of serverless endpoints. Whether you're developing a RESTful API, a web service, or a complex backend system, PhotonIQ Functions offers a flexible and scalable solution.
In this section, you'll learn how to send HTTP requests to an external API using functions. We'll demonstrate this by making a GET request to the "Return pet inventory" endpoint and a POST request to the "Create User" endpoint using the popular Petstore API. Select your preferred programming language from the tabs below to continue with the next steps.
- Next.js
- Javascript
Sending a POST request with Next.js functions
To create a new function in your Next.js app,
Create a
/api/post/route.js
in the/src/app
directory.Then, add the following snippet to define an endpoint that sends a request to the Create User endpoint and returns either the result or an error message.
import { NextResponse } from 'next/server';
export async function POST(request) {
console.log('Executing function...');
try {
const body = await request.json();
const newObj = {
'username': body.username,
'email': body.email,
'password': body.password,
'userStatus': 1
};
const apiResponse = await fetch('https://petstore.swagger.io/v2/user', {
method: 'POST',
headers: {
"Authorization": `api_key ${body.apiKey}`,
"Accept": 'application/json',
"Content-Type": 'application/json'
},
body: JSON.stringify(newObj)
});
if (apiResponse.ok) {
const data = await apiResponse.json();
console.log(`User created with key [${data.message}]`);
return NextResponse.json({
message: `PhotonIQ FaaS function is working => Env Var MESSAGE = ${process.env.MESSAGE}`,
key: data.message
}, { status: 200 });
} else {
return NextResponse.json(
{ error: `Failed to save data. Status code: ${apiResponse.status}` },
{ status: 500 }
);
}
} catch (error) {
console.error(`Error: ${error.message}`);
return NextResponse.json(
{ error: `Failed to send request API: ${error.message}` },
{ status: 500 }
);
}
}
export async function GET() {
return NextResponse.json({ message: 'Method not allowed' }, { status: 405 });
}
Test the function locally
Before testing the function, build your Next.js project with the recent changes using:
faas build <project-name>
Once the build is successful, serve the app by running:
faas run <project-name>
This command will start the local server on http://localhost:8080
by default.
To test the function, send a POST request to the appropriate route on your local server. For example, using curl
:
curl --location 'http://localhost:8080/api/post' \
--header 'Content-Type: application/json' \
--data-raw '{
"username": "test",
"email": "test@test.com",
"password": "hola"
}'
If successful, the response will include the key generated by the Create User endpoint and the message from the MESSAGE
environment variable defined in the photoniq.toml
file:
{
"message": "PhotonIQ FaaS function is working => Env Var MESSAGE = Hello 👋! This message comes from an environment variable",
"key": "9223372036854758628"
}
Sending a GET request with Next.js functions
To define another function in your Next.js app for the GET request,
Create a
/api/get/route.ts
in the/src/app
directory.Add the following code to send a GET request to the Return pet inventory endpoint and return the response.
import { NextRequest, NextResponse } from 'next/server';
export async function GET(request: NextRequest) {
// Log messages with the following methods: error, warn, info, debug, trace
console.trace(`[${__filename}] Executing function...`);
try {
// Send a GET request to the specified URL
const apiResponse = await fetch('https://petstore.swagger.io/v2/store/inventory', {
method: 'GET',
headers: {
'Accept': 'application/json',
},
});
// Check the response result
if (apiResponse.status === 200) {
const inventory = await apiResponse.json();
console.info(`[${__filename}] Inventory fetched successfully`);
// Return the response
return new NextResponse(JSON.stringify(inventory), {
status: 200,
headers: {
'Content-Type': 'application/json',
},
});
} else {
return new NextResponse(JSON.stringify({ error: `Failed to fetch inventory. Status code: ${apiResponse.status}` }), {
status: 500,
headers: {
'Content-Type': 'application/json',
},
});
}
} catch (error) {
console.error(`[${__filename}] Error: ${error}`);
return new NextResponse(JSON.stringify({ error: `Failed to send request to API: ${error}` }), {
status: 500,
headers: {
'Content-Type': 'application/json',
},
});
}
}
Test the function locally
To test your function locally, start by building your Next.js project with the recent changes using:
faas build <project-name>
Once the build is successful, serve the app by running:
faas run <project-name>
This will server the app on localhost:8080
by default.
You can then navigate to the endpoint route on the local server URL in your browser (http://localhost:8080/api/get
), where the response will display the inventory data from the API.
Alternatively, you can run the function directly from the command line with:
faas execute <project_name>
The command above executes the function and shows the result of the GET request. You can also send a GET request to the local server using curl
:
curl --location http://localhost:8080'
Sending a POST request with Javascript functions
The default template code in index.js
processes a POST request to create a user by sending data to the Create User endpoint and returns a response with the result or an error message.
addEventListener("handler", async (event) => {
// Log messages with the following methods: error, warn, info, debug, trace
log.trace(`[${file_line()}] Executing function...`);
// Control the HTTP method used
if (event.request.method != HttpMethod.POST) {
return event.respondWith(
getErrorResult(`Method not allowed`)
);
}
// Use the environment variables like MESSAGE below
let response = {
message: `PhotonIQ FaaS function is working => Env Var MESSAGE = ${MESSAGE}`
};
try {
// Get the request body calling `json()` or `text()` functions
const body = event.request.json();
let newObj = {
'username': body.username,
'email': body.email,
'password': body.password,
'userStatus': 1
};
// Use the HttpRequestBuilder for requesting HTTP calls
let apiResponse = await new HttpRequestBuilder('https://petstore.swagger.io/v2/user')
.method(HttpMethod.POST)
.header("Authorization", `api_key ${body.apiKey}`)
.header("Accept", 'application/json')
.header("Content-Type", 'application/json')
.body(newObj)
.build()
.send();
// Check the response result
if (apiResponse.status === 200) {
let key = apiResponse.json().message;
log.info(`[${file_line()}] User created with key [${key}]`);
response.key = key;
// Use the HttpResponseBuilder for returning the function result
return event.respondWith(new HttpResponseBuilder().body(response).build());
} else {
return event.respondWith(
getErrorResult(`Failed to save data. Status code: ${apiResponse.status}`)
);
}
} catch (error) {
return event.respondWith(
getErrorResult(`Failed to send request API: ${error.message}`)
);
}
});
function getErrorResult(message) {
log.error(`[${file_function_line()}] Error: ${message}`);
return new HttpResponseBuilder()
.status(500)
.body(`Error => ${message}`)
.build()
}
Test the function locally
To test the POST request function and create a user, start by running:
faas run <project-name>
This command will start the local server, hosted on http://localhost:8080
by default.
Next, send a POST request to this local server URL with the appropriate user data. For example, using curl
:
curl --location 'http://localhost:8080' \
--header 'Content-Type: application/json' \
--data-raw '{
"username": "test",
"email": "test@test.com",
"password": "hola"
}'
If successful, the response will include the key generated by the Create User endpoint and the message from the MESSAGE
environment variable in photoniq.toml
:
{
"message": "PhotonIQ FaaS function is working => Env Var MESSAGE = Hello 👋! This message comes from an environment variable",
"key": "9223372036854758628"
}
Sending a GET request with Javascript functions
To send a GET request to the Return pet inventory endpoint, replace the contents of index.js
with the snippet below:
addEventListener("handler", async (event) => {
// Log messages with the following methods: error, warn, info, debug, trace
log.trace(`[${file_line()}] Executing function...`);
try {
// Send a GET request to the specified URL
let apiResponse = await new HttpRequestBuilder('https://petstore.swagger.io/v2/store/inventory')
.method(HttpMethod.GET)
.header("Accept", 'application/json')
.build()
.send();
// Check the response result
if (apiResponse.status === 200) {
let inventory = apiResponse.json();
log.info(`[${file_line()}] Inventory fetched successfully`);
// Use the HttpResponseBuilder for returning the function result
return event.respondWith(new HttpResponseBuilder().body(inventory).build());
} else {
return event.respondWith(
getErrorResult(`Failed to fetch inventory. Status code: ${apiResponse.status}`)
);
}
} catch (error) {
return event.respondWith(
getErrorResult(`Failed to send request to API: ${error.message}`)
);
}
});
function getErrorResult(message) {
log.error(`[${file_function_line()}] Error: ${message}`);
return new HttpResponseBuilder()
.status(500)
.body(`Error => ${message}`)
.build()
}
Test the function locally
To test the GET request function locally, start by running:
faas run <project-name>
This command will start the local server, hosted on http://localhost:8080
by default. Navigate to this local server URL in your browser to view the inventory data result from the API.
Alternatively, you can execute the function directly from the command line with:
faas execute <project_name>
This command runs the function and displays the result of the GET request in your terminal.
You can also send a GET request to the route on your local server using curl
:
curl --location 'http://localhost:8080'
When you execute faas run
, the terminal remains open and returns log messages from the function.
With PhotonIQ Functions, you can now extend your APIs to handle various methods and build sophisticated backend systems. For advanced steps, consider integrating other HTTP methods or configuring additional APIs to enhance your application’s functionality. The next section will introduce you to configuring PhotonIQ Functions