Skip to main content

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.

Sending a POST request with Next.js functions

To create a new function in your Next.js app,

  1. Create a /api/post/route.js in the /src/app directory.

  2. 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,

  1. Create a /api/get/route.ts in the /src/app directory.

  2. 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'
tip

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