Bird
Raised Fist0
Astroframework~10 mins

Server endpoints (API routes) in Astro - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Server endpoints (API routes)
Client sends HTTP request
↓
Server endpoint matches route
↓
Run endpoint handler function
↓
Process request data
↓
Generate response data
↓
Send HTTP response back to client
↓
Client receives response
This flow shows how a client request hits a server endpoint, which processes it and sends back a response.
Execution Sample
Astro
export async function GET() {
  return new Response(JSON.stringify({ message: 'Hello from API' }), {
    status: 200,
    headers: { 'Content-Type': 'application/json' }
  });
}
This code defines a GET API route that returns a JSON message with status 200.
Execution Table
StepActionInputOutputNotes
1Client sends GET request/api/helloRequest receivedRequest arrives at server endpoint
2Server matches route/api/helloMatched GET handlerGET function is selected
3Execute GET handlerNo bodyResponse object createdResponse with JSON message is prepared
4Send responseResponse objectHTTP 200 with JSON bodyResponse sent back to client
5Client receives responseHTTP 200 with JSON{ message: 'Hello from API' }Client can use the JSON data
💡 Request handled fully; response sent back to client
Variable Tracker
VariableStartAfter Step 3Final
requestundefinedGET request objectGET request object
responseundefinedResponse object with JSONResponse object with JSON
Key Moments - 2 Insights
Why do we return a Response object instead of just data?
The Response object includes status and headers, not just data. See execution_table step 3 where the Response is created with JSON and status 200.
What happens if the route does not match any endpoint?
The server returns a 404 error automatically because no handler runs. This is before step 2 in the execution_table.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the output at step 3?
AResponse object created with JSON message
BRequest received from client
CHTTP 404 error
DRoute matching failed
💡 Hint
Check the 'Output' column in row for step 3 in execution_table
At which step does the server send the response back to the client?
AStep 1
BStep 4
CStep 2
DStep 5
💡 Hint
Look for 'Send response' action in execution_table
If the GET handler returned status 404 instead of 200, how would the output at step 4 change?
ANo response sent
BHTTP 200 with JSON body
CHTTP 404 with JSON body
DRequest would be retried
💡 Hint
Step 4 output shows the HTTP status code sent in the response
Concept Snapshot
Server endpoints handle HTTP requests.
Define functions like GET, POST for routes.
Return Response objects with status, headers, and body.
Server matches route, runs handler, sends response.
Client receives JSON or other data from response.
Full Transcript
Server endpoints in Astro handle HTTP requests by matching the request route to a handler function like GET. When a client sends a request, the server finds the matching endpoint and runs its handler. The handler processes the request and returns a Response object containing status, headers, and body data. The server sends this response back to the client, which receives the data. If no route matches, the server returns a 404 error. This flow ensures clients get the correct data or error from the server.

Practice

(1/5)
1. What is the main purpose of a server endpoint in Astro?
easy
A. To manage client-side routing
B. To style the website pages
C. To handle incoming HTTP requests and send responses
D. To store user data permanently

Solution

  1. Step 1: Understand what server endpoints do

    Server endpoints are designed to receive requests from clients and send back data or responses.
  2. Step 2: Differentiate from other roles

    Styling, client routing, and data storage are handled elsewhere, not by server endpoints.
  3. Final Answer:

    To handle incoming HTTP requests and send responses -> Option C
  4. Quick Check:

    Server endpoints = handle requests [OK]
Hint: Endpoints handle requests and responses, not styling or routing [OK]
Common Mistakes:
  • Confusing endpoints with client-side routing
  • Thinking endpoints style pages
  • Assuming endpoints store data permanently
2. Which of the following is the correct way to export a GET handler in an Astro server endpoint?
easy
A. function get() { return 'Hello' }
B. export async function GET(context) { return new Response('Hello') }
C. export function get() { return 'Hello' }
D. export async GET() { return 'Hello' }

Solution

  1. Step 1: Recall Astro endpoint syntax

    Astro expects exported async functions named by HTTP method in uppercase, e.g., GET.
  2. Step 2: Check function signature and export

    export async function GET(context) { return new Response('Hello') } correctly exports an async function named GET with a context parameter and returns a Response object.
  3. Final Answer:

    export async function GET(context) { return new Response('Hello') } -> Option B
  4. Quick Check:

    Export async uppercase method function = export async function GET(context) { return new Response('Hello') } [OK]
Hint: Export async functions named GET/POST in uppercase for endpoints [OK]
Common Mistakes:
  • Using lowercase function names
  • Not exporting the function
  • Missing async keyword
  • Returning string instead of Response object
3. Given this Astro endpoint code, what will be the response body when a GET request is made?
export async function GET() {
  return new Response(JSON.stringify({ message: 'Hi' }), { headers: { 'Content-Type': 'application/json' } })
}
medium
A. undefined
B. Hi
C. Error: Missing context parameter
D. {"message":"Hi"}

Solution

  1. Step 1: Analyze the returned Response object

    The function returns a Response with JSON stringified object { message: 'Hi' } and content-type application/json.
  2. Step 2: Determine response body content

    The response body will be the JSON string: {"message":"Hi"} exactly as stringified.
  3. Final Answer:

    "{\"message\":\"Hi\"}" -> Option D
  4. Quick Check:

    JSON.stringify output = {"message":"Hi"} [OK]
Hint: JSON.stringify returns string, so response body is JSON text [OK]
Common Mistakes:
  • Expecting plain text 'Hi' instead of JSON string
  • Confusing response body with object
  • Thinking context parameter is mandatory
4. What is wrong with this Astro endpoint code?
export function POST(request) {
  const data = await request.json();
  return new Response('Received');
}
medium
A. The function must be async to use await
B. POST should be lowercase
C. request.json() is not a valid method
D. Response must be an object, not a string

Solution

  1. Step 1: Check async usage with await

    The function uses await but is not declared async, causing a syntax error.
  2. Step 2: Verify other parts

    POST must be uppercase and exported, request.json() is valid, and Response can take a string body.
  3. Final Answer:

    The function must be async to use await -> Option A
  4. Quick Check:

    Use async with await = The function must be async to use await [OK]
Hint: Use async keyword when using await inside functions [OK]
Common Mistakes:
  • Forgetting async keyword with await
  • Using lowercase HTTP method names
  • Misunderstanding request.json() availability
5. You want to create an Astro server endpoint that accepts a POST request with JSON data containing a "name" field, and responds with a JSON greeting like { "greeting": "Hello, name!" }. Which code snippet correctly implements this?
hard
A. export async function POST({ request }) { const data = await request.json(); return new Response(JSON.stringify({ greeting: `Hello, ${data.name}!` }), { headers: { 'Content-Type': 'application/json' } }); }
B. export function POST(request) { const data = request.json(); return new Response({ greeting: 'Hello, ' + data.name + '!' }); }
C. export async function POST(request) { const data = await request.text(); return new Response(JSON.stringify({ greeting: 'Hello, ' + data + '!' })); }
D. export async function POST() { return new Response(JSON.stringify({ greeting: 'Hello!' })); }

Solution

  1. Step 1: Check correct async POST function with destructured request

    export async function POST({ request }) { const data = await request.json(); return new Response(JSON.stringify({ greeting: `Hello, ${data.name}!` }), { headers: { 'Content-Type': 'application/json' } }); } correctly exports async POST with { request } destructured to access request.json().
  2. Step 2: Verify JSON parsing and response format

    export async function POST({ request }) { const data = await request.json(); return new Response(JSON.stringify({ greeting: `Hello, ${data.name}!` }), { headers: { 'Content-Type': 'application/json' } }); } awaits request.json(), extracts name, and returns JSON response with proper headers.
  3. Final Answer:

    export async function POST({ request }) { const data = await request.json(); return new Response(JSON.stringify({ greeting: `Hello, ${data.name}!` }), { headers: { 'Content-Type': 'application/json' } }); } -> Option A
  4. Quick Check:

    Async POST with request.json() and JSON response = export async function POST({ request }) { const data = await request.json(); return new Response(JSON.stringify({ greeting: `Hello, ${data.name}!` }), { headers: { 'Content-Type': 'application/json' } }); } [OK]
Hint: Use async POST with await request.json() and JSON response headers [OK]
Common Mistakes:
  • Not awaiting request.json()
  • Returning Response with object instead of string
  • Missing Content-Type header for JSON
  • Not destructuring request parameter
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard