skip to Main Content

I have NextJs front from which i need to do calls to external python api. I’m new to Next and i just found out that there is integrated api (by creating folders app/api/resource/route). So what is the proper way to call external resource?

  1. Do it just using fetch/axios as you’d did it in react?

  2. Call NextJs’s integrated api and then redirect from that to external?

Does second variant make any sense at all or am I tweakin?

2

Answers


  1. You can evaluate both options by looking at their pros and cons.

    You should use API routes if you are accessing some resources that you don’t want to be exposed to on the client side or if you want to do any background work.

    You can go with Axios/fetch if you don’t have any resources to hide and don’t want to add a layer of API routes and processing. Both options have their pros and cons; you can refer to some guides about that.

    Login or Signup to reply.
  2. The proper way to call an external API from your Next.js application is by using the built-in API routes feature or by making HTTP requests directly from your Next.js frontend code.

    If you decide to use the built-in API routes feature in Next.js, you can create a new file in the pages/api directory and define the route handlers for your external API calls in that file. You can then make requests to this API route from your frontend code using the fetch API or any other HTTP client library.

    Alternatively, you can directly make HTTP requests to the external API from your Next.js frontend code using the fetch API or any other HTTP client library. You can handle the response from the external API directly in your frontend code and render the data as needed.

    Here is an example of how you can make an API call to an external resource from your Next.js frontend code using the fetch API:

    const fetchData = async () => {
      try {
        const response = await fetch('https://api.example.com/data');
        if (!response.ok) {
          throw new Error('Failed to fetch data');
        }
        
        const data 
    
    = await response.json();
        console.log(data);
      } catch (error) {
        console.error(error);
      }
    };
    
    fetchData();
    

    Remember to handle any errors that may occur during the API call and to properly handle the response data in your frontend code.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search