Notes on RESTful APIs and Building with Express.js
Introduction to APIs
- API Definition: Application Programming Interface, a method for computers to communicate.
- Interaction with API: Similar to using a website, but requests are coded.
- Example: Use NASA's REST API to request JSON data on asteroids.
RESTful APIs
- REST: Representational State Transfer, the standard for API development since early 2000s.
- Resources: Organized into URIs (Uniform Resource Identifiers).
- HTTP Requests:
- GET: Read data
- POST: Create new resource
- PATCH: Update resource
- DELETE: Remove resource
- Request Format:
- Start line with HTTP verb and URI
- Headers (e.g., Accept, Authorization)
- Body with custom data payload
- Response Format:
- Status code (200s: success, 400s: client error, 500s: server error)
- Headers with response information
- Body usually in JSON
- Stateless Architecture: Every request/response is independent.
Building a RESTful API with Express.js
- Express.js: Popular framework for building RESTful APIs in Node.js.
- Setup:
- Use VS Code, have Node.js installed (version 12 used).
- Run
npm init -y
to create package.json
.
- Install Express with
npm install express
.
- Create
index.js
file.
- Basic API Structure:
- Import Express and initialize:
const app = require('express')()
.
- Listen on port:
app.listen(8080)
.
- Check API in browser or use tools like Insomnia or Postman.
Creating API Endpoints
- GET Request:
- Create endpoint:
app.get('/t-shirt', callbackFunction)
.
- Handle request with
req
and send response with res
.
- POST Request:
- Dynamic URL parameter for unique resource ID.
- Use
req.params
for URL parameters and req.body
for request body.
- Setup middleware to parse JSON:
app.use(express.json())
.
- Check for required data (e.g., logo) and respond accordingly.
Error Handling and Response
- Use status codes (e.g., 200 for success, 418 for error with missing data).
- Test API with Insomnia: check requests and responses.
OpenAPI Specification
- Purpose: Standard to describe APIs in YAML.
- Benefits:
- Fully document APIs for easy use.
- Generate client/server-side code automatically.
- Compatible with tools like AWS API Gateway for security and monitoring.
- Tools: Swagger Hub for code generation and documentation.
Conclusion
- RESTful APIs are essential for building reliable web applications.
- Express.js offers a minimal and effective framework for API development in Node.js.
- OpenAPI enhances API documentation and integration capabilities.
Consider exploring more advanced content and tutorials on building APIs using the OpenAPI spec and cloud services.