Leaderboard

Hi, the component compiler will only generate C# stub components if your typescript follows a few rules. One of those is that it must be declared like this: export class YourScript extends Behaviour where the Behaviour imported from Needle Engine. Please take a look at the docs at Needle Engine Scripting | Needle Engine Documentation for more info about all that

Thanks, it now looks like this, but I get an “Uncaught SyntaxError: Cannot use import statement outside a module (at apiCall.ts:1:1)” error in the browser console.

import { Behaviour } from “@needle-tools/engine”;

export class apiTest2 extends Behaviour {
async Start() {
const url = ‘https://x8ki-letl-twmt.n7.xano.io/api:gIB1bPgH/user’;
const options = {
method: ‘POST’,
headers: {
‘Content-Type’: ‘application/json’
},
body: JSON.stringify({})
};

    try {
        const response = await fetch(url, options);
        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
        }
        const data = await response.json();
        console.log('ID:', data.id); // Log the 'id' value from the response
    } catch (error) {
        console.error('Error during API call:', error);
    }
}

}

by user 507643794963824650

I was able to do it in a new project in Unity in C#. So I know where I’m wrong, just not what is wrong :frowning_with_open_mouth:

by user 507643794963824650

Starting to understand the docs a little better, it might be a missing dependency from NPM, I tried installing a few different npm packages, no luck yet. I triad Axios and Fetch, installing them, then using an API call. Also tried using a javascript file.

by user 507643794963824650

@Needle Engine Assistant is it possible to make an external API request in Needle? I already have an API endpoint set up. Should I use typescript or a JavaScript file for this?

by user 507643794963824650

Here is what I found for you :brain: Discord

Hello 0nederful,

Yes, it is possible to make an external API request in Needle Engine using TypeScript, which is the primary language for scripting in Needle Engine. You would typically use the built-in fetch API in JavaScript along with TypeScript’s async/await pattern to handle the request.

Here is a step-by-step pseudocode plan:

  1. Import the required TypeScript types and modules.
  2. Create a new TypeScript class that extends Behaviour.
  3. Implement the start lifecycle method.
  4. Inside start, use fetch to make an asynchronous request to the API endpoint.
  5. Process the response and handle it as needed.

Now, I’ll provide you with example code:

import { Behaviour } from '@needle-tools/engine';

export class ApiRequestExample extends Behaviour {
    async start() {
        try {
            const response = await fetch('https://your-api-endpoint.com/data');
            if (!response.ok) throw new Error('Network response was not ok.');
            const data = await response.json();
            // Use your API data as needed
        } catch (error) {
            console.error('There has been a problem with your fetch operation:', error);
        }
    }
}

Make sure the endpoint in the fetch function is replaced with your actual API endpoint URL. Keep in mind that for this to work, the server your API is hosted on must have CORS (Cross-Origin Resource Sharing) enabled to allow your Needle Engine application to make requests to it.

If you have any more questions or need further assistance, feel free to ask.

1 messages left GPT 4
thread_04a2K3cqDuQgNnU2uEP54iYu
Thanks for your feedback!

@Needle Engine Assistant Do I need to import the fetch dependency from npm too?

by user 507643794963824650

Yes, the fetch API is supported in modern web browsers and does not require an additional import from npm. It can be used directly in TypeScript code within Needle Engine for making HTTP requests to API endpoints.

If you have any more questions or need further assistance, feel free to ask.

0 messages left GPT 3.5
thread_04a2K3cqDuQgNnU2uEP54iYu

Where did you add this script too? From the warning it sounds like this is not the right place (should be in „src“ in your web project or in an NpmDef).
You don’t need to install anything to use fetch

Hi, I put it under /src/scripts/ like all my other scripts that have to convert to C# - this should go in the same spot as the others, or no?

I did see there’s another /src/ folder under /engine/src/

Would be great to know if that script works for anyone else. Appreciate your help!

by user 507643794963824650

Your scripts go into src/scripts if you want c# components to be generated

OK, that’s what I’ve been doing. I couldn’t find a template that does any sort of simple API call like this (among your list of wonderful examples). Are you able to drop it in /scripts/ and see if it converts for you? I’d be glad to pay you or someone to have a working API call script.

I also tried creating a new project and get the same result. Other scripts generate just fine for me.

by user 507643794963824650

Did you try the one the bot suggested above? It’s perfectly fine and should work like that.

Yes, getting compilation failed. When I try to create another known-good script after that it will continue to fail until I delete that API script. When I delete it, my other scrips will generate fine.

by user 507643794963824650

How does your script look and which error do you get in unity?

I’m able to get this working in Typescript playground

import { Behaviour } from '@needle-tools/engine';

// Define the async function to fetch data from the API
async function fetchData(apiUrl: string): Promise<void> {
  try {
    // Make a GET request using the fetch API
    const response = await fet
ch(apiUrl);

    // If the response is not ok, throw an error
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }

    // Parse the JSON response
    const data = await response.json();
    
    // Log the data to the console
    console.log(data);
  } catch (error) {
    // Log any errors that occur during the fetch
    console.error('Error fetching data: ', error);
  }
}

// Call the fsetchData function with the API endpoint URL
fetchData('https://x8ki-letl-twmt.n7.xano.io/api:gIB1bPgH/user');

It seems to just get hung, screenshot included.

I tried the bot’s code (as well as a few others), here it is, and will include screenshot for that as well.

import { Behaviour } from '@needle-tools/engine';

export class ApiRequestExample extends Behaviour {
    async start() {
        try {
            const response = await fetch('https://x8ki-letl-twmt.n7.xano.io/api:gIB1bPgH/user');
            if (!response.ok) throw new Error('Network response was not ok.');
            const data = await response.json();
            // Use your API data as needed
        } catch (error) {
            console.error('There has been a problem with your fetch operation:', error);
        }
    }
}


by user 507643794963824650

You can also just create a c# script manually. Name it ApiRequestExample and add it to one of your gameobjects in the scene.

@Needle Engine Assistant I am learning that I can create c# scripts manually instead of having to use Typescript that has to be converted to C# in Needle. Do I have to put these manually built c# scripts anywhere specific, like in /src/scripts, or can they go anywhere in my project?

Can you generate a C# script that will make an API call to any publicly available endpoint, and display the output to the console.

by user 507643794963824650

Here is what I found for you :brain: Discord