#Get searchparams from url in API endpoint

9 messages · Page 1 of 1 (latest)

slate cipherBOT
#

Hi @urban valve. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:

#

In Astro, you can access the URL of the current endpoint using the request property. However, in static mode, you only have access to request.url. This returns the full URL of the current endpoint. Here's an example of how you can use it:

import type { APIRoute } from 'astro';

export const GET: APIRoute = ({ params, request }) => {  
  const url = new URL(request.url);
  const src = url.searchParams.get('src');
  
  return new Response(JSON.stringify({      
    src: src
  }));
}

In this example, request.url is used to create a new URL object. The URL object's searchParams property is then used to get the value of the src parameter from the URL.

Please note that this will only work in development mode or server-side rendering mode. In static mode, the request object does not contain search parameters like ?src=image.jpg, as it's not possible to determine them ahead of time during static builds.

For more information, you can refer to the Astro documentation (https://docs.astro.build/en/guides/endpoints/#request).

Note: you can ask me a follow up question by @ mentioning me again :speech_balloon:

#

@urban valve kapa.ai is still learning and improving, please let us know how it did by reacting below

urban valve
slate cipherBOT
#

Let me check the knowledge base for you. One moment! :books:

#

I see, it seems like you're encountering an issue where the request.url does not contain the search parameters in the server logs. This is likely due to the fact that in Astro's static mode, the request.url does not contain search parameters like ?src=image.jpg. This is because it's not possible to determine them ahead of time during static builds.

However, you mentioned that this endpoint will only work in dev mode. In output: 'server' mode, Astro.request.url does contain search parameters as it can be determined from a server request.

If you're running this in dev mode and still not seeing the search parameters, it might be a bug or an unexpected behavior. In such cases, it would be best to reach out to the Astro community or support for further assistance.

For more information, you can refer to the Astro documentation (https://docs.astro.build/en/reference/api-reference/#astrorequest).

Note: you can ask me a follow up question by @ mentioning me again :speech_balloon:

#

@urban valve kapa.ai is still learning and improving, please let us know how it did by reacting below

urban valve
#

@slate cipher Ok. So in dev mode, emulate as output is server?

slate cipherBOT
#

Let me check the knowledge base for you. One moment! :books: