- When we want to just communicate data with the server and not HTML.
3 example use cases
- Client (Mobile App)
- Client (Code, features like maps)
- Client (Browser w/SPA)
It has endpoints, with each endpoints having individual HTTP verbs. (methods)
- AJAX request
- Get response
The JSON data will be transfered here for request and response.
- Client Server Architecture Seperation of concerns , RESTful API should not care about UI
- Stateless No Client-Context ( eg: no sessions ) is stored on the server
- Cacheabilty Responses must define themselves are cacheable or non-cacheable
- Layered System Intermediate Servers maybe used without the client knowing about it
- Uniform Interface
- Resources are identified in requests, transferred data is decoupled from db schema.
- Self descriptive messages, links to further resources returned from server are essential
- Code on Demand (Optional) Executable code could be transferred.
- Plan the endpoints, with the methods.
- Mark the protected routes
Some packages:
nodemon, morgan - logging package, body-parser
What are CORS? Cross - origin resource sharing
If the client and server are on the same server, like say localhost:3000 Then it will succeed. But for a restful API, the client and server has different origins, so the request will fail. So for restful Api, we want to allow access.
So we have to disable this mechanism , by sending some headers to the server from the client
Maintain a documentation, and clearly state about the data and data format. That is the request and response data
How is works?
Client ----------------- Server
Client sends auth data (email, pwd) to server for registration or login
Then in a normal node app we return a session, but we dont use sessions in restapi servers, and even mobile appps cannot use sessions, we will actually return a Token. This token can be stored by our clients, and the client uses this token for future requests, we verify the token and serve the request
This token is a JWT : JSON WEB TOKEN Its a JSON Data + Signature = JWT
This signature can be verified
We will use a private+public key combination. JSON data is not encryptied
steps:
- start by creating a user model
- implement signup, use bcrypt
- implement login
- use jsonwebtoken npm package for JWT
- return JWT token on login
using middlewares that checks for a valid token and continue only if the token is valid
Send the token in header with
Key --------------------- Value
Authorization ------------ Bearer [jwt]