You can find a summary of the code updates in this pull request . Read on for explanations.
1. Create the route.ts file
We need to create a route handler : an endpoint that can be contacted via HTTP. In the next workshop in this series, we’ll contact this route handler from the client side.
The goal is to call the endpoint api/get-quote-styles
for this route handler. That means we need to create a file here: src/app/api/get-quote-styles/route.ts. (A note on the endpoint name: we’re only getting a random quote for now; the “style” will come in the next series).
2. Create a GET function
This route handler will handle GET requests, so we’ll name the function GET
.
route.ts
3. Get random quote
The function will return a random quote. We’ll get the random quote using the (conveniently named) getRandomQuote
function from src/helpers/random-quotes.ts:
route.ts
4. Return JSON
Eventually (in the next series), we’re going to return a more complicated response than just a quote, so we’ll need to structure the response using JSON . However, even if we’re only returning a quote, it’s still useful to return JSON. JSON helps determine on the client end whether the response is valid – if we’re looking for a property in the response and it’s not there, chances are something went wrong.
We’ll use the NextResponse.json method to return the JSON.
route.ts
5. Access the route handler
Let’s see what we’ve got. To access the endpoint:
- Run
npm run dev
from the top level of the app in the terminal. - Access http://localhost:3000/api/get-quote-styles to hit the endpoint and see the result in your browser. Since you’re retrieving a random quote, the response should be different every time you refresh this page.
The page in the browser will be raw JSON, something like this (your quote will probably differ since it’s randomly selected!):
We’ll take care of those grammatical errors in the next series (AI Style Generator). 😁
Up next
In the next workshop, we’ll fetch data from this endpoint and display it in the UI.
Workshops in this series
- Quotation endpoint
- Display fetched data
- Loading state
- Error state
- Custom hook
- Conditional rendering