REST API
Introduction
Waldemar Panas - Bachelor of Engineering at PUT
- Professional programmer
for 6 years
- Currently Software Developer
at Allegro
- Where to find me?
- https://wpanas.github.com
- https://twitter.com/PanasWaldemar
Agenda I. What is MVC?
II. What is REST API?
III. What MVC does better
than REST API?
IV. How REST API can fix it?
What is MVC? - Structure of application design
- Decouples data layer
from presentation layer
- Introduces the chance
for parallel development
of front-end and back-end
Model
- Data layer
- Domain logic
- Persistency
class StudentModel: Model {
void insert(Student student);
void update(Student student);
Student findOne(String id);
Set<Student> findAll();
}
View
- Presentation layer
- Generated HTML
- Reusable templates
<h1>List of students</h1>
<ul>
{{foreach student is students}}
<li>
<a href="/editStudent/{{student.id}}">
{{student.name}}
</a>
</li>
{{endforeach}}
</ul>
{{template: footer}}
Forms
Forms as means to input data to the system
<form action="/saveStudent" method="post">
<label for="firstname">First name:</label>
<input type="text" id="firstname" name="firstname">
<label for="lastname">Last name:</label>
<input type="text" id="lastname" name="lastname">
<input type="submit" value="Submit">
</form>
Links
Links as means to navigate across the system
<a href="/listStudents">Students</a>
<a href="/addStudent">Add new student</a>
<a href="/editStudent/1">Edit student: John Doe</a>
Students
Add new student
Edit student: John Doe
Controller
- Binds Model
with View
- Actions to interact
with application
- The less logic,
the better
- GET for displaying
- POST for changing
class StudentController: Controller {
final StudentModel model
@GET
Response listStudents() {
var students = model.findAll();
return Response(
view="list-students",
data=[students]
)
}
}
What is REST API? 1. REpresentational State Transfer
2. Structure of application
architecture design
3. Principles
4. What for?
Client-Server
RESTAPI
Web
Android
iOS
Uniform Interface - 2xx - Everything’s good
- 200 OK
- 201 CREATED
- 202 ACCEPTED
- 204 NO CONTENT
- 4xx - Your request is invalid
- 400 BAD REQUEST
- 401 UNAUTHORIZED
- 403 FORBIDDEN
- 404 NOT FOUND
- 415 UNSUPPORTED MEDIA TYPE
- 422 UNPROCESSABLE ENTITY
- 5xx - Ups… My bad. Try again!
- 500 INTERNAL SERVER ERROR
- 503 SERVICE UNAVAILABLE
HTTP Codes
Uniform Interface
{
"firstName": "John",
"lastName": "Doe",
"address": {
"city": "Warsaw",
"country": "Poland"
},
"hobbies": [
"drawing",
"cycling"
]
}
Media Type - JSON
- It’s everywhere
- Simple & easy to read for humans
- Flexible
Uniform Interface - Accept vs Content-Type
- application/json
- application/vnd.wpanas+json
- application/hal+json
- application/xml
- Accept-Language vs
Content-Language
- pl_PL
- en_EN
- Custom headers X-My-Header
HTTP headers
Uniform Interface
{method} "/{collection}/{identifier}/{element}"
- method - GET, POST, PUT, DELETE
- collection - books, invoices, orders, products - plural nouns
- identifier - 544, 8257b0b2-5b11-4998-9d5f-9ff49ed4e9c4
- element - author, positions, payment, attributes - plural or singular nouns
Examples
- GET /books/9788025122853/author
- POST /invoices/FA123564/positions
- PUT /orders/9419b9fd-3dc7-44ed-a7b1-ae77be190660/payment
Resource-based
Request GET /students/1
Accept: application/json
Response 200 OK
Content-Type: application/json
{
"firstName": "John",
"lastName": "Doe"
}
- Fetch resource
- Idempotent
- No side-effects
- Response
- 200 OK with response body
Resource-based
Request POST /students
Content-Type: application/json
{
"firstName": "John",
"lastName": "Doe"
}
Response 201 CREATED
Location: /student/2
- Create resource
- Not idempotent
- Response
- 201 Created with header Location
- 200 OK with resource body
- Update resource
- Create resource
if client decides about id
- Idempotent because
whole resource in request
- Response
- 204 No content
- 202 Accepted
Resource-based
Request PUT /students/1
Content-Type: application/json
{
"id": "1"
"firstName": "John",
"lastName": "Doe"
}
Response 204 NO CONTENT
Resource-based
Request DELETE /students/1
Response 204 NO CONTENT
- Delete resource
- Response
- 204 No Content
- 202 Accepted
- After deletion
- 404 Not found
- 410 Gone
Stateless
RESTAPI
Server 1
Server 2
Database Cluster
Stateless
Request POST /authorize
Accept: application/json
Response 200 OK
Content-Type: application/json
{
"token": "secret"
}
Request PUT /students/1
Content-Type: application/json
Authorization: Bearer secret
{
"id": "1"
"firstName": "John",
"lastName": "Doe"
}
Response 204 NO CONTENT
Layered
RESTAPI
Student Resource
Authorization
Resource
MongoDB
Redis
PostgreSQL
Cacheable
Request GET /students/1
Accept: application/json
Response 200 OK
Content-Type: application/json
Cache-Control: public, max-age=3600
E-tag: RandomHashSfgdfgdasd
Expires: Mon, 18 Nov 2019 20:00:00 GMT
Cacheable
Request GET /students/1
Accept: application/json
If-None-Match: RandomHashSfgdfgdasd
Response 304 Not Modified
Simplicity, Scalability & Portability
RESTAPI
Server 1
Server 2
Database Cluster
CLIENT
CACHE
What MVC does better
than REST API?
Decouples presentation layer
from application logic
Example
Content-Type: application/json
{
"id": "1"
"firstName": "John",
"lastName": "Doe",
"status": "applicant"
}
Student life at the university
- If applicant
- accept
- decline
- If accepted
- pay tuition
- expel
- If expelled or declined
- archive
1. Logic must be implemented
on all clients
2. New status needs to be
implemented on all clients
3. In this form status is an enum,
not a string!
- You can’t change it
without braking clients!
4. Android & iOS have long
release procedures
5. Mobile users don’t have to
update their clients
Client-Server
coupling
How REST API can fix
client-server coupling?
Hypermedia as the Engine of Application State
HATEOAS
Content-Type: application/hal+json
{
"id": "1"
"firstName": "John",
"lastName": "Doe",
"status": "applicant",
"_links": {
"accept": { "href": "/student/10/acceptance", "type": "POST" },
"decline": { "href": "/student/10", "type": "DELETE" }
}
}
Why HATEOAS? - Shows interactions
with current resource
- Decouples server logic
from client
- Living documentation
Summary - REST API is:
- structure of application architecture
design
- based on client-server communication,
uniform interface and resources
- cacheable
- layered
- stateless
- great, because provides us with
simplicity, scalability & portability
- excellent, if you use HATEOAS
What next? - Tools
- Swagger
- Postman / Newman
- Consumer Driven Contracts
- What else?
- CQRS
- GraphQL

REST API Introduction

  • 1.
  • 2.
    Waldemar Panas -Bachelor of Engineering at PUT - Professional programmer for 6 years - Currently Software Developer at Allegro - Where to find me? - https://wpanas.github.com - https://twitter.com/PanasWaldemar
  • 3.
    Agenda I. Whatis MVC? II. What is REST API? III. What MVC does better than REST API? IV. How REST API can fix it?
  • 4.
    What is MVC?- Structure of application design - Decouples data layer from presentation layer - Introduces the chance for parallel development of front-end and back-end
  • 5.
    Model - Data layer -Domain logic - Persistency class StudentModel: Model { void insert(Student student); void update(Student student); Student findOne(String id); Set<Student> findAll(); }
  • 6.
    View - Presentation layer -Generated HTML - Reusable templates <h1>List of students</h1> <ul> {{foreach student is students}} <li> <a href="/editStudent/{{student.id}}"> {{student.name}} </a> </li> {{endforeach}} </ul> {{template: footer}}
  • 7.
    Forms Forms as meansto input data to the system <form action="/saveStudent" method="post"> <label for="firstname">First name:</label> <input type="text" id="firstname" name="firstname"> <label for="lastname">Last name:</label> <input type="text" id="lastname" name="lastname"> <input type="submit" value="Submit"> </form>
  • 8.
    Links Links as meansto navigate across the system <a href="/listStudents">Students</a> <a href="/addStudent">Add new student</a> <a href="/editStudent/1">Edit student: John Doe</a> Students Add new student Edit student: John Doe
  • 9.
    Controller - Binds Model withView - Actions to interact with application - The less logic, the better - GET for displaying - POST for changing class StudentController: Controller { final StudentModel model @GET Response listStudents() { var students = model.findAll(); return Response( view="list-students", data=[students] ) } }
  • 10.
    What is RESTAPI? 1. REpresentational State Transfer 2. Structure of application architecture design 3. Principles 4. What for?
  • 11.
  • 12.
    Uniform Interface -2xx - Everything’s good - 200 OK - 201 CREATED - 202 ACCEPTED - 204 NO CONTENT - 4xx - Your request is invalid - 400 BAD REQUEST - 401 UNAUTHORIZED - 403 FORBIDDEN - 404 NOT FOUND - 415 UNSUPPORTED MEDIA TYPE - 422 UNPROCESSABLE ENTITY - 5xx - Ups… My bad. Try again! - 500 INTERNAL SERVER ERROR - 503 SERVICE UNAVAILABLE HTTP Codes
  • 13.
    Uniform Interface { "firstName": "John", "lastName":"Doe", "address": { "city": "Warsaw", "country": "Poland" }, "hobbies": [ "drawing", "cycling" ] } Media Type - JSON - It’s everywhere - Simple & easy to read for humans - Flexible
  • 14.
    Uniform Interface -Accept vs Content-Type - application/json - application/vnd.wpanas+json - application/hal+json - application/xml - Accept-Language vs Content-Language - pl_PL - en_EN - Custom headers X-My-Header HTTP headers
  • 15.
    Uniform Interface {method} "/{collection}/{identifier}/{element}" -method - GET, POST, PUT, DELETE - collection - books, invoices, orders, products - plural nouns - identifier - 544, 8257b0b2-5b11-4998-9d5f-9ff49ed4e9c4 - element - author, positions, payment, attributes - plural or singular nouns Examples - GET /books/9788025122853/author - POST /invoices/FA123564/positions - PUT /orders/9419b9fd-3dc7-44ed-a7b1-ae77be190660/payment
  • 16.
    Resource-based Request GET /students/1 Accept:application/json Response 200 OK Content-Type: application/json { "firstName": "John", "lastName": "Doe" } - Fetch resource - Idempotent - No side-effects - Response - 200 OK with response body
  • 17.
    Resource-based Request POST /students Content-Type:application/json { "firstName": "John", "lastName": "Doe" } Response 201 CREATED Location: /student/2 - Create resource - Not idempotent - Response - 201 Created with header Location - 200 OK with resource body
  • 18.
    - Update resource -Create resource if client decides about id - Idempotent because whole resource in request - Response - 204 No content - 202 Accepted Resource-based Request PUT /students/1 Content-Type: application/json { "id": "1" "firstName": "John", "lastName": "Doe" } Response 204 NO CONTENT
  • 19.
    Resource-based Request DELETE /students/1 Response204 NO CONTENT - Delete resource - Response - 204 No Content - 202 Accepted - After deletion - 404 Not found - 410 Gone
  • 20.
  • 21.
    Stateless Request POST /authorize Accept:application/json Response 200 OK Content-Type: application/json { "token": "secret" } Request PUT /students/1 Content-Type: application/json Authorization: Bearer secret { "id": "1" "firstName": "John", "lastName": "Doe" } Response 204 NO CONTENT
  • 22.
  • 23.
    Cacheable Request GET /students/1 Accept:application/json Response 200 OK Content-Type: application/json Cache-Control: public, max-age=3600 E-tag: RandomHashSfgdfgdasd Expires: Mon, 18 Nov 2019 20:00:00 GMT
  • 24.
    Cacheable Request GET /students/1 Accept:application/json If-None-Match: RandomHashSfgdfgdasd Response 304 Not Modified
  • 25.
    Simplicity, Scalability &Portability RESTAPI Server 1 Server 2 Database Cluster CLIENT CACHE
  • 26.
    What MVC doesbetter than REST API? Decouples presentation layer from application logic
  • 27.
    Example Content-Type: application/json { "id": "1" "firstName":"John", "lastName": "Doe", "status": "applicant" } Student life at the university - If applicant - accept - decline - If accepted - pay tuition - expel - If expelled or declined - archive
  • 28.
    1. Logic mustbe implemented on all clients 2. New status needs to be implemented on all clients 3. In this form status is an enum, not a string! - You can’t change it without braking clients! 4. Android & iOS have long release procedures 5. Mobile users don’t have to update their clients Client-Server coupling
  • 29.
    How REST APIcan fix client-server coupling? Hypermedia as the Engine of Application State
  • 30.
    HATEOAS Content-Type: application/hal+json { "id": "1" "firstName":"John", "lastName": "Doe", "status": "applicant", "_links": { "accept": { "href": "/student/10/acceptance", "type": "POST" }, "decline": { "href": "/student/10", "type": "DELETE" } } }
  • 31.
    Why HATEOAS? -Shows interactions with current resource - Decouples server logic from client - Living documentation
  • 32.
    Summary - RESTAPI is: - structure of application architecture design - based on client-server communication, uniform interface and resources - cacheable - layered - stateless - great, because provides us with simplicity, scalability & portability - excellent, if you use HATEOAS
  • 33.
    What next? -Tools - Swagger - Postman / Newman - Consumer Driven Contracts - What else? - CQRS - GraphQL