W
Wasp-langβ€’6mo ago
marc

How does one go about creating their own server-side API endpoint to interact with in the frontend?

wasp version 0.13.2 Platform: MacOS Hey! Quick question, is there documentation lying around somewhere regarding a guide to creating your own API endpoint in order to interact with it in the frontend without messing with authorizations and backend logic? For context, I modified the OpenSaaS GenerateGPTResponse function in the server/actions.ts boilerplate to fit my custom application needs (for the app I'm trying to build). Problem is, I dont know how to proceed to call this function from the client/DemoAppPage.tsx file. I'm sure there are other server-side files that need changing, but is there a checklist of things to modify I could refer to by chance? Or else, if there is maybe a useful video/tutorial I'd be happy to try and figure it out for myself. Thanks in advance!! PS: not a web dev originally! Very unfamiliar with Typescript and there might be something obvious I'm missing out on πŸ™‚
4 Replies
kapa.ai
kapa.aiβ€’6mo ago
Hi @marc. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave: ---------------------- Sure, I can guide you through the process of creating your own API endpoint in Wasp and then using it in the frontend. Here are the steps: 1. Declare the API in Wasp: You need to declare the API in your Wasp file using the api declaration. This ties a JS function to a certain endpoint. Here's an example:
// main.wasp
api fooBar {
fn: import { fooBar } from "@src/apis",
httpRoute: (GET, "/foo/bar")
}
// main.wasp
api fooBar {
fn: import { fooBar } from "@src/apis",
httpRoute: (GET, "/foo/bar")
}
In this example, fooBar is the name of the API, and it's associated with the fooBar function from the @src/apis file. The httpRoute specifies the HTTP method (GET) and the path ("/foo/bar") for the API. source (https://wasp-lang.dev/docs/advanced/apis) 2. Define the API's NodeJS implementation: After declaring the API, you need to implement it as a NodeJS function. This function should take three arguments: req (Express Request object), res (Express Response object), and context (an additional context object injected into the API by Wasp). Here's an example:
// src/apis.js
export const fooBar = (req, res, context) => {
res.set("Access-Control-Allow-Origin", "*"); // Example of modifying headers to override Wasp default CORS middleware.
res.json({ msg: `Hello, ${context.user ? "registered user" : "stranger"}!` });
};
// src/apis.js
export const fooBar = (req, res, context) => {
res.set("Access-Control-Allow-Origin", "*"); // Example of modifying headers to override Wasp default CORS middleware.
res.json({ msg: `Hello, ${context.user ? "registered user" : "stranger"}!` });
};
In this example, fooBar is the function that implements the API. It modifies the headers to override Wasp's default CORS middleware and sends a JSON response. source (https://wasp-lang.dev/docs/advanced/apis#defining-the-apis-nodejs-implementation) 3. Use the API from the client: To use the API from your client, you can import the Axios wrapper from wasp/client/api and invoke a call. Here's an example:
// src/pages/SomePage.jsx
import React, { useEffect } from "react";
import { api } from "wasp/client/api";

async function fetchCustomRoute() {
const res = await api.get("/foo/bar");
console.log(res.data);
}

export const Foo = () => {
useEffect(() => {
fetchCustomRoute();
}, []);

return <>// ...</>;
};
// src/pages/SomePage.jsx
import React, { useEffect } from "react";
import { api } from "wasp/client/api";

async function fetchCustomRoute() {
const res = await api.get("/foo/bar");
console.log(res.data);
}

export const Foo = () => {
useEffect(() => {
fetchCustomRoute();
}, []);

return <>// ...</>;
};
In this example, fetchCustomRoute is an async function that calls the API and logs the response data. It's called inside a useEffect hook in the Foo component. source (https://wasp-lang.dev/docs/advanced/apis#using-the-api-from-the-client) Remember to ensure that CORS (Cross-Origin Resource Sharing) is enabled to use these APIs on the client side. You can do this by defining custom middleware for your APIs in the Wasp file. source (https://wasp-lang.dev/docs/advanced/apis#making-sure-cors-works) I hope this helps! If you run into any issues, feel free to ask. ---------------------- Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: ---------------------- Sorry @marc, 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
Filipβ€’6mo ago
Hi @marc, seems like the bot answered the question of defining a custom API (outside of Wasp's RPC system of Queries and Actions). I'm not sure that's what you wanted. From what I understood, you seem need a regular Action. Or is there something else you need that an Action doesn't cover? In case you don't know what an Action is, I suggest you read our docs since they are the core feature of Wasp. Go through either: - The tutorial - it introduces you to all the most important features and is pretty fast. - The docs on Operations - A proper documentation page on Operations, the core feature of Wasp
marc
marcβ€’6mo ago
Thanks for your reply @sodic ! Starting to realize the wasp js docs can be useful when building from the OpenSaaS templates, I had thought those were two parallel frameworks. I'll take a look and get back to you if I run into any issues!
Filip
Filipβ€’6mo ago
Oh, I realize the confusion. We should probably somehow emphasize that OpenSaas is just a template repo written in Wasp, it's not a framework or anything. @Vinny (@Wasp) Something to think about when you get back πŸ™‚ OpenSaas is just a Wasp project that you can use as a starting point, nothing more. OpenSaas is to Wasp is what create-react-app is to React (albeit much richer), and OpenSaas docs are just there to "onboard" you onto the pre-written code of OpenSaas.
Want results from more Discord servers?
Add your server