Api requested from external wasp app

How do I implement an api from my wasp app that sends data to an external application?
13 Replies
kapa.ai
kapa.ai4w ago
Hi @Bruno Njeru. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave: ---------------------- To implement an API in your Wasp app that sends data to an external application, you should: 1. Create a custom API endpoint in your Wasp app using the api declaration in your main.wasp file. This will expose an HTTP endpoint that can be called from external applications or from your own client/server code. 2. Implement the API handler in your server code. In this handler, you can use Node.js libraries (like axios or fetch) to send data to the external application. Example 1. Declare the API in main.wasp:
api sendDataToExternal {
fn: import { sendDataToExternal } from "@src/apis",
httpRoute: (POST, "/send-data")
}
api sendDataToExternal {
fn: import { sendDataToExternal } from "@src/apis",
httpRoute: (POST, "/send-data")
}
2. Implement the API handler in src/apis.js:
import axios from 'axios';

export const sendDataToExternal = async (req, res, context) => {
const data = req.body; // Data sent to your Wasp API

try {
// Send data to the external application
const response = await axios.post('<https://external-app.com/api/endpoint',> data);

// Respond to the original caller
res.json({ success: true, externalResponse: response.data });
} catch (error) {
res.status(500).json({ success: false, error: error.message });
}
};
import axios from 'axios';

export const sendDataToExternal = async (req, res, context) => {
const data = req.body; // Data sent to your Wasp API

try {
// Send data to the external application
const response = await axios.post('<https://external-app.com/api/endpoint',> data);

// Respond to the original caller
res.json({ success: true, externalResponse: response.data });
} catch (error) {
res.status(500).json({ success: false, error: error.message });
}
};
3. Use the API from your client or call it externally: - From your Wasp client, use the Axios wrapper to call /send-data. - From an external app, make a POST request to your Wasp app's /send-data endpoint. This approach allows your Wasp app to act as a proxy, receiving data and forwarding it to an external service as needed. You can also add authentication, validation, or any other logic in your API handler. For more details, see the official Wasp documentation on Custom HTTP API Endpointssource, including defining the API's NodeJS implementationsource. ---------------------- Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: ---------------------- Sorry @Bruno Njeru, I seem to be having a bit of trouble. Don't worry though, I've pinged my support and they will try to fix me up! :technologist: Perhaps try again in 15mins?
Bruno Njeru
Bruno NjeruOP4w ago
How would I set the api in the external app (it's also a wasp app) @kapa.ai
kapa.ai
kapa.ai4w ago
Let me check the knowledge base for you again. One moment! :books: ---------------------- To set up an API in your external Wasp app (so that your main Wasp app can send data to it), you need to: 1. Declare the API endpoint in the external app's main.wasp file using the api declaration. 2. Implement the API handler in the external app's server code (e.g., in src/apis.js or src/apis.ts). Example 1. In the external app's main.wasp:
api receiveData {
fn: import { receiveData } from "@src/apis",
httpRoute: (POST, "/receive-data")
}
api receiveData {
fn: import { receiveData } from "@src/apis",
httpRoute: (POST, "/receive-data")
}
2. In the external app's src/apis.js:
export const receiveData = (req, res, context) => {
// Access the data sent from the other Wasp app
const received = req.body;
// Do something with the data (e.g., save to DB, process, etc.)
res.json({ success: true, received });
};
export const receiveData = (req, res, context) => {
// Access the data sent from the other Wasp app
const received = req.body;
// Do something with the data (e.g., save to DB, process, etc.)
res.json({ success: true, received });
};
3. Your main Wasp app can now send a POST request to <https://external-app-domain/receive-data.> This setup is the same as creating any custom API endpoint in Wasp, as described in the Custom HTTP API Endpoints documentationsource. If you need to use entities or authentication, you can add the entities and auth fields to the api declaration as needed. For more details, see the API Referencesource. If you need to call this API from the client or from another server, you simply make an HTTP request to the endpoint you defined, as described in Using the API externallysource. If you need CORS support (for cross-origin requests), make sure to configure the appropriate middleware as described in the CORS sectionsource. ---------------------- Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: ---------------------- Sorry @Bruno Njeru, I seem to be having a bit of trouble. Don't worry though, I've pinged my support and they will try to fix me up! :technologist: Perhaps try again in 15mins?
Bruno Njeru
Bruno NjeruOP4w ago
What about the data sent from my wasp app, how do I get the data from the db and post it to the external app? Can you show an example @kapa.ai
kapa.ai
kapa.ai4w ago
Let me check the knowledge base for you again. One moment! :books: ---------------------- To send data from your Wasp app's database to an external Wasp app, you should: 1. Fetch the data from your database using a Wasp Query or directly in your API handler via Prisma (through the context.entities object). 2. Send the data to the external app using an HTTP client (like axios) in your API handler. Here’s a concrete example: 1. Declare the API in your Wasp app (main.wasp):
api sendTasksToExternal {
fn: import { sendTasksToExternal } from "@src/apis",
entities: [Task],
httpRoute: (POST, "/send-tasks")
}
api sendTasksToExternal {
fn: import { sendTasksToExternal } from "@src/apis",
entities: [Task],
httpRoute: (POST, "/send-tasks")
}
This allows your API handler to access the Task entity via context.entities.Tasksource. 2. Implement the API handler (src/apis.js or src/apis.ts):
import axios from 'axios';

export const sendTasksToExternal = async (req, res, context) => {
// Fetch data from your database using Prisma via context.entities
const tasks = await context.entities.Task.findMany({});

try {
// Send the data to the external Wasp app's endpoint
const response = await axios.post('<https://external-app-domain/receive-data',> tasks);

res.json({ success: true, externalResponse: response.data });
} catch (error) {
res.status(500).json({ success: false, error: error.message });
}
};
import axios from 'axios';

export const sendTasksToExternal = async (req, res, context) => {
// Fetch data from your database using Prisma via context.entities
const tasks = await context.entities.Task.findMany({});

try {
// Send the data to the external Wasp app's endpoint
const response = await axios.post('<https://external-app-domain/receive-data',> tasks);

res.json({ success: true, externalResponse: response.data });
} catch (error) {
res.status(500).json({ success: false, error: error.message });
}
};
- Here, context.entities.Task.findMany({}) fetches all tasks from your database, using the Prisma client injected by Waspsource. - The data is then sent to the external app’s /receive-data endpoint using axios. This approach leverages Wasp’s built-in entity access in APIs and standard Node.js HTTP libraries to forward data to another service. If you need to filter or transform the data before sending, you can adjust the Prisma query or process the tasks array as needed. Note: The knowledge sources do not provide a full end-to-end example with axios, but they do show how to access entities in APIs and how to use custom API endpoints in Waspsource. ---------------------- Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: ---------------------- Sorry @Bruno Njeru, I seem to be having a bit of trouble. Don't worry though, I've pinged my support and they will try to fix me up! :technologist: Perhaps try again in 15mins?
Bruno Njeru
Bruno NjeruOP4w ago
What about authorization in the external app @kapa.ai
kapa.ai
kapa.ai4w ago
Let me check the knowledge base for you again. One moment! :books: ---------------------- Authorization in the external Wasp app is currently something you need to implement yourself. Wasp does not yet provide built-in, fine-grained authorization (like RBAC) out of the box, but you can easily add your own logic. A common approach is to add a role field to your User entity and then, in your API handler, check the user's role (or any other relevant property) before allowing access or performing actions. If the user is not authorized, you can throw an HTTP 403 error. Here’s a summary of the recommended approach: - Add a role field to your User entity. - In your API handler, check the user's role or other properties via context.user. - If unauthorized, throw an error (e.g., HttpError(403)). Example from the Wasp community:
You can add role field to User entity, and you can then in your queries/actions check the value of that role and based on that make a decision if they should be able to execute that query/action or not. If they are not allowed, you can throw HttpError 403 or something like that.
Discord: How do you add authorization? Wasp plans to add more advanced authorization features in the future, but for now, this manual approach is the standard way to handle authorization in your APIs. ---------------------- Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: ---------------------- Sorry @Bruno Njeru, I seem to be having a bit of trouble. Don't worry though, I've pinged my support and they will try to fix me up! :technologist: Perhaps try again in 15mins?
Bruno Njeru
Bruno NjeruOP4w ago
So the external api has no authorisation/authentication @kapa.ai
kapa.ai
kapa.ai4w ago
Let me check the knowledge base for you again. One moment! :books: ---------------------- Based on the knowledge sources, Wasp does not provide built-in, automatic authorization or authentication for custom API endpoints by default. However, you can enable authentication for an API endpoint by setting the auth: true field in your api declaration in main.wasp. When auth is enabled, Wasp will attempt to parse the JWT in the Authorization header and provide a context.user object in your API handler. You can then implement your own authorization logic by checking properties of context.user (such as a role field) in your handler code. If you do not set auth: true, the API endpoint will not require authentication, and context.user will be undefined. This means anyone can call the endpoint unless you implement your own checks. Here is the relevant part from the documentation:
If auth is enabled, this will default to true and provide a context.user object. If you do not wish to attempt to parse the JWT in the Authorization Header, you should set this to false source.
For more advanced authorization (e.g., role-based access), you need to implement the logic yourself in the API handler, as Wasp does not yet provide built-in RBAC or similar systems source. In summary:
By default, a custom API in Wasp has no authorization/authentication unless you explicitly enable it and implement the necessary logic in your handler. ---------------------- Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: ---------------------- Sorry @Bruno Njeru, I seem to be having a bit of trouble. Don't worry though, I've pinged my support and they will try to fix me up! :technologist: Perhaps try again in 15mins?
Bruno Njeru
Bruno NjeruOP4w ago
How can I implement this logic @kapa.ai
MEE6
MEE64w ago
Wohooo @Bruno Njeru, you just became a Waspeteer level 7!
kapa.ai
kapa.ai4w ago
Let me check the knowledge base for you again. One moment! :books: ---------------------- To implement authentication and authorization for a custom API endpoint in your external Wasp app, follow these steps: --- 1. Enable Auth for the API Endpoint In your external app's main.wasp, set auth: true in the api declaration. This ensures that Wasp will parse the JWT from the Authorization header and provide a context.user object in your handler.
api receiveData {
fn: import { receiveData } from "@src/apis",
httpRoute: (POST, "/receive-data"),
auth: true
}
api receiveData {
fn: import { receiveData } from "@src/apis",
httpRoute: (POST, "/receive-data"),
auth: true
}
If auth is enabled, this will default to true and provide a context.user object. If you do not wish to attempt to parse the JWT in the Authorization Header, you should set this to false (API Reference).
--- 2. Implement Authorization Logic in the Handler In your API handler (e.g., src/apis.js), check for context.user and any additional authorization logic you need (such as checking a role field):
import { HttpError } from 'wasp/server';

export const receiveData = (req, res, context) => {
// Authentication check
if (!context.user) {
throw new HttpError(401); // Not authenticated
}

// Example: Authorization check (e.g., only allow admins)
if (context.user.role !== 'admin') {
throw new HttpError(403); // Forbidden
}

// Proceed with your logic
const received = req.body;
res.json({ success: true, received });
};
import { HttpError } from 'wasp/server';

export const receiveData = (req, res, context) => {
// Authentication check
if (!context.user) {
throw new HttpError(401); // Not authenticated
}

// Example: Authorization check (e.g., only allow admins)
if (context.user.role !== 'admin') {
throw new HttpError(403); // Forbidden
}

// Proceed with your logic
const received = req.body;
res.json({ success: true, received });
};
You can add role field to User entity, and you can then in your queries/actions check the value of that role and based on that make a decision if they should be able to execute that query/action or not. If they are not allowed, you can throw HttpError 403 or something like that (Discord: How do you add authorization?).
--- 3. Summary - Set auth: true in your API declaration to enable authentication. - Use context.user in your handler to check authentication and implement custom authorization logic. - Throw HttpError(401) for unauthenticated users and HttpError(403) for unauthorized users. This approach is the current best practice in Wasp for securing custom API endpoints, as more advanced built-in authorization features are planned for future releases but are not available yet. ---------------------- Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: ---------------------- Sorry @Bruno Njeru, I seem to be having a bit of trouble. Don't worry though, I've pinged my support and they will try to fix me up! :technologist: Perhaps try again in 15mins?
Filip
Filip4w ago
@Bruno Njeru All good here? Need human help? If so, please tag @miho. He's covering for me while I'm away 🙂

Did you find this page helpful?