Developing your API
In this section, we'll cover how you can create the API routes to support our example chatroom application. We'll create our API routes that we defined in the earlier page
All the code used here is pulled from the NextJS docs on API routes using the Pages router.
For each API route, I'll include some code for how to read the response using fetch()
.
Notes
- Everything below is usually an initial stage of developing your web API.
- Because this is a prototype, there's plenty of things we can ignore now and address later, like security and other application constraints.
Create a User
pages/api/user.js
export default async function handler(req, res) {
const session = await getServerSession(req, res)
if (req.method === 'POST') {
// Handle POST request
const name = req.body.name
await db.createUser(name)
return res.status(201).json({name})
} else {
return res.status(501).json({ message: 'Not implemented yet' })
}
}
Make a request
fetch('/api/user', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({name: 'danny'})
}).then(response => response.text())
.then(body => console.log(body))
Create a Chatroom
Note - this is copied from the previous section. Included for completeness.
pages/api/chatroom/index.js
export default async function handler(req, res) {
const session = await getServerSession(req, res)
if (req.method === 'POST') {
// Handle POST request
const name = req.body.name
await db.createChatroom(name)
return res.status(201).json({name})
} else {
return res.status(501).json({ message: 'Not implemented yet' })
}
}
Make the request
fetch('/api/chatroom', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({name: 'class-channel'})
}).then(response => response.text())
.then(body => console.log(body))
Join a Chatroom
pages/api/chatroom/[name].js
export default async function handler(req, res) {
const session = await getServerSession(req, res)
if (req.method === 'PUT') {
const name = req.body.name
await db.createUser(name)
return res.status(201).json({name})
} else {
return res.status(501).json({ message: 'Not implemented yet' })
}
}
app.put('/chatroom/:name', (request, response) => {
const chatroomName = request.params.name
const userName = request.body.userName
const chatroom = db.getChatroom(chatroomName)
if (!chatroom) {
response.status(404).send('Chatroom not found')
// return to prevent the rest of the code from running
return
}
db.joinChatroom(userName, chatroomName)
response.status(200).send()
})
info
- The
:
defines a route parameter (param for short) /chatroom/:name
creates a param namedname
, and any text thats passed in there will be assigned to that param./chatroom/class-channel
creates areq.params.name
property, equal toclass-channel
- We can check if the chatroom exists by using a
getChatroom(chatroomName)
function. - We can set a
404
status code by callingresponse.status(404).send()
Make a request
fetch('/chatroom/class-channel', {
method: 'PUT',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ userName: 'danny' })
}).then(response => {
if (response.statusCode === 200) {
console.log('Joined chatroom')
return
} else {
console.log('Received response: ', response.statusCode)
return response.text().then(body => {
console.log('Received body', body)
})
}
})
info
- When you're reading the response for a
fetch()
request, you can look at theresponse.statusCode
property to see the status code for the request - In this case, if it doesn't respond with a 200, then we look at the request body for more information.
Send a Message
app.js
app.post('/chatroom/:name/message', (request, response) => {
const chatroomName = request.params.name
const message = request.body.message
const userName = request.body.userName
if (!message) {
response.status(400).send('missing message')
return
} else if (!userName) {
response.status(400).send('mising userName')
return
}
const chatroom = db.getChatroom(chatroomName)
if (!chatroom) {
response.status(404).send('Chatroom not found')
// return to prevent the rest of the code from running
return
}
db.sendMessage(userName, chatroomName, message)
response.status(201).send()
})
info
- If the
message
property was missing from the request body, we can send back a400
Bad Request with an error message. - Likewise for the
userName
property - We can also validate that the chatroom exists before trying to create the message, and send back a
404
if the chatroom doesnt exist
Make a request
fetch('/chatroom/class-channel/message', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ userName: 'danny', message: 'hello!' })
}).then(response => {
if (response.statusCode === 201) {
console.log('Sent message')
return
} else {
console.log('Received response: ', response.statusCode)
return response.text().then(body => {
console.log('Received body', body)
})
}
})