Week 4: Building Your First FHIR Endpoint in Node.js
Michael Planchart
Healthcare Chief Architect and Data Engineer| Databricks | HL7, FHIR | AI/ML | NLP, NLU, BERT, T5, GPT, LLAMA
Welcome to Week 4 of the DIY FHIR Server Training Series. With a solid understanding of FHIR fundamentals, a well-planned architecture, and a development environment ready to go, it is time to roll up our sleeves and build your first FHIR endpoint.
This week’s focus is on creating RESTful endpoints using Node.js and Express.js for handling Patient resources. You will implement two essential methods: GET to retrieve patient data and POST to create new patients. Along the way, we will introduce concepts like route handling, middleware, and in-memory data storage to simulate a real-world API.
By the end of this chapter, you will have built a functional API capable of basic Patient resource interactions, a critical milestone in constructing your FHIR server.
Recap of Week 3
Last week, you set up your development environment, installed the necessary tools, and structured your project folder. These foundational steps have prepared you to dive into API development. If you have not completed those tasks, revisit Week 3 to ensure you are ready to proceed.
Recommended Project Folder Structure
Before diving into coding, let us establish a well-organized folder structure for your FHIR server project. This structure will keep your code modular and maintainable as the project grows:
fhir-server/
|
├── backend/ # Backend code and logic
| ├── routes/ # API route definitions
| │ └── patientRoutes.js
| ├── services/ # Business logic and data management
| │ └── patientService.js
| ├── middlewares/ # Middleware for validation and error handling
| ├── server.js # Main server file
|
├── database/ # Scripts for database configuration
| └── dbConfig.js
├── tests/ # Unit and integration tests
| └── patient.test.js
|
├── Dockerfile # Docker container configuration
├── README.md # Project documentation
└── package.json # Node.js dependencies and metadata
Prerequisites
Before starting this week, ensure you have:
Note: For simplicity, this week’s lesson will use in-memory data storage. Persistent storage will be introduced in future chapters.
Detailed Topics for This Week
a. Setting Up Express.js and Creating a Basic RESTful Endpoint
1. Install Express.js
Express.js simplifies the creation of web applications and APIs in Node.js.
Run the following command to install Express in your project:
npm install express
2. Initialize Your Express Server
Navigate to your backend folder and create a file called server.js.
Add the following Javascript code:
const express = require('express');
const app = express();
const PORT = 3000;
// Middleware to parse incoming JSON requests
app.use(express.json());
// Root endpoint
app.get('/', (req, res) => {
res.send('Welcome to the FHIR server!');
});
// Start the server
app.listen(PORT, () => {
console.log(`Server is running on https://localhost:${PORT}`);
});
Run the server using the command node server.js and open https://localhost:3000 in your browser or Postman. You should see the message: Welcome to the FHIR server!
3. Create a Router for Patient Resources
To keep your code modular, navigate to backend/routes and create a file called patientRoutes.js:
const express = require('express');
const router = express.Router();
const patients = [];
// Get all patients
router.get('/', (req, res) => {
res.json(patients);
});
// Add a new patient
router.post('/', (req, res) => {
const newPatient = req.body;
if (!newPatient.id || !newPatient.name) {
return res.status(400).json({ error: 'Missing required fields: id, name' });
}
patients.push(newPatient);
res.status(201).json(newPatient);
});
module.exports = router;
Integrate this router in server.js by adding:
领英推荐
const patientRoutes = require('./routes/patientRoutes');
app.use('/Patient', patientRoutes);
4. Test Your Endpoints
Use Postman to send GET and POST requests to https://localhost:3000/Patient. For the POST request, use the following JSON payload:
{
"id": "1",
"name": "Jane Doe",
"gender": "female",
"birthDate": "1990-05-15"
}
Verify that the GET endpoint returns the new patient you just created.
b. Implementing Enhanced Functionality for Patient Resources
1. Querying Patients by ID Add support for retrieving a specific patient by their ID:
// Get a patient by ID
router.get('/:id', (req, res) => {
const patient = patients.find(p => p.id === req.params.id);
if (!patient) {
return res.status(404).json({ error: 'Patient not found' });
}
res.json(patient);
});
Test this by sending a GET request to https://localhost:3000/Patient/1.
2. Error Handling Implement error handling to improve the user experience:
app.use((err, req, res, next) => {
console.error(err.stack);
res.status(500).json({ error: 'An internal server error occurred' });
});
3. Data Validation Use middleware to validate incoming POST requests:
function validatePatient(req, res, next) {
const { id, name } = req.body;
if (!id || !name) {
return res.status(400).json({ error: 'Missing required fields: id, name' });
}
next();
}
router.post('/', validatePatient, (req, res) => {
const newPatient = req.body;
patients.push(newPatient);
res.status(201).json(newPatient);
});
Fire Side Chats: Tips for Success
Takeaway Assignments
1. Enhance the GET Method:
Add support for filtering patients by gender or birthDate using query parameters.
2. Implement PUT and DELETE Endpoints:
Create endpoints to update and delete Patient resources. Ensure you validate data before updating.
3. Explore Middleware:
Write custom middleware for logging request details (e.g., method, endpoint, timestamp).
4. Document Your API:
Write documentation for your Patient endpoints using tools like Swagger or even a simple Markdown file.
Next Steps
Now that you’ve successfully built your first FHIR endpoint in Node.js, the next step is to ensure the data handled by your server is accurate and compliant with FHIR standards. In Week 5, you’ll focus on validating FHIR resources using Python.
You’ll learn to use libraries for resource validation, write Python scripts to detect errors, and enforce compliance with FHIR specifications. This critical step ensures that your server processes only well-formed data, paving the way for reliable and interoperable operations. Prepare to enhance the robustness of your server as we dive into validation!
Data Analyst
1 个月Thanks for your sharing! I just applied your instruction to build my own server. I think "app.use" in 2. Error Handling should be changed to "router.use" to be consistent. Thank you.
GenOp? Software: The Premier Solution to Healthcare Interoperability?
2 个月Thanks for sharing!