Demonstrating some facility with REST APIs and what you can do with them. I also talk about the client-side AJAX code that's bringing this all together for a better user experience.
Find it live at app.samliebl.com.
- REST API demos
- Note on the client-side JavaScript (AJAX functionality)
- App
- Directory structure
- Routes & notes on paths
--
- Demonstration of a
GETAPI call/request- Rendering the site with Nunjucks via Express
- Three Demonstrations of
POSTAPI call/requests- A simple
POSTAPI call/request - A more complex
POSTrequest - Number lookup with Twilio carrier lookup API
POSTrequest
- A simple
--
The app itself works via the server.js file in the home directory.
.
├╴ .env¹
├╴ .env.example²
├╴ views/
│ ├╴ _layouts/
│ │ └╴ base.njk
│ ├╴ _partials/
│ │ ├╴ client-side-js.njk
│ │ ├╴ get-render.njk
│ │ ├╴ lookup-form.njk
│ │ ├╴ nav.njk
│ │ ├╴ post-simple.njk
│ │ └╴ post-whisper.njk
│ ├╴ index.njk
│ └╴ error.njk
├╴ public/
│ ├╴ css/
│ │ └╴ main.css
│ └╴ js/
│ └╴ main.js
├╴ routes/
│ ├╴ download-transcription.js
│ ├╴ home.js
│ ├╴ index.js
│ ├╴ lookup.js
│ ├╴ submit.js
│ └╴ transcribe.njk
├╴ uploads/³
└╴ server.js
---
Notes:
1. You will add your own
2. As an example, with placeholder data, for what yours would look like
3. where the audio files & transcription takes place
Take a look at the source code—mostly in server.js and then in the templates directory (views/) for the client-side code.
Each route/API request is modularized into its own route in a routes/ directory. There's a routes/index.js that collects all the route modules and exports them up to server.js, which in turn puts them in the mix like so...
app.use('/', routes);The transcription feature allows users to download a plain text file of the transcription. To support this, there's an uploads/ directory located at the project's root level. Since path resolution within routes/ files can be tricky (e.g., __dirname resolves to the routes/ directory), the app uses a middleware function defined before app.use() for the routes. This middleware attaches the project root path to the request object as req.projectRoot. By consistently using req.projectRoot to construct paths in route handlers, we ensure that all file operations (e.g., reading or writing in uploads/) reliably point to the correct directory, regardless of where the route files are located.
// Use modularized routes
app.use((req, res, next) => {
req.projectRoot = projectRoot; // Attach project root to request object
next();
});MIT