개발자 끄적끄적
RestAPI 본문
<What is REST?>
- REST stands for REpresentational State Transfer
- An architectural 'style' for developing web services
- REST is a web standards based architecture and uses 'HTTP' Protocol for data communication
- It revolves around 'resources' which are accessed by a common interface using HTTP standard methods
ex)
Client -> (URI, GET) http://weather.example.com/seoul -> Server(Resource(Seoul))
Server -> (Representation) seoul weather -> Client
- In REST architecture, a REST Server simply provides access to resources and the REST client accesses and presents the resources
- Each resource is identified by URIs/ Global IDs
- REST uses various representations to represent a resource like Text, JSON and XML
- JSON is now the most popular format being used in Web Services
ex)
Client -> Request Method(GET/POST/PUT/DELETE) -> Server
Server -> Response Format(JSON or XML) -> Client
ex) Example : Web service called User Management
HTTP Method URI Operation
GET /api/users retuns a list of users
GET /api/users/1 returns the user with ID 1
POST /api/users creates a new user
PUT /api/users/3 updates the user with ID 3
DELETE /api/users/4 deletets the user with ID 4
DELETE /api/users delete all the users
<RESTful Web Services>
- Web services based on REST Architecture are known as RESTful Web Services
- Decoupling + Platform Agnostic
- Notice that pattern :
- A set of commands(mehtods)
- performed on things(resource)
- generates responses(message)
-> This is the foundation of a REST API
<RESTful 이란?>
- HTTP와 URI 기반으로 자원에 접근할 수 있도록 제공하는 애플리케이션 개발 인터페이스
- 기본적으로 개발자는 HTTP 메소드와 URI 만으로 인터넷에 자료를 CRUD 할 수 있다.
- 'REST API'를 제공하는 웹 서비스를 'RESTful' 하다고 할 수 있다.
<RESTful Web Services(Resource)>
- Representation of Resources
ex) xml
<user>
<id>1</id>
<name>Mahesh</name>
<profession>Teacher</profession>
</user>
ex) JSON
{
"id":1,
"name":"Mahesh",
"profession":"Teacher"
}
<Simple JSON Exmaple>
- Curley braces define objects Object members are name / value pairs
- Delimited by colons
- Name is always in double-quotes
- JSON Values
- Numbers: no quotes
- String: in double quotes
- Boolean: true, false
- Nested JSON object
- Array
- null
- ex)
{
"id": 14,
"lastName": "Rossi",
"active": true,
"languages" : ["Java", "Python", "Javascript"], //Array
"address" : { //Nested(계층형)
"street" : "100 Main St",
"city" : "Philadelphia",
"state" : "Pennsylvania",
"zip" : "19103",
"country" : "USA“
}
}
- ex) Nested(계층형) JSON은 다음 같은 형식을 말한다(response 필드)
이 때, Nested 필드의 필드명이 JSON의 필드명과 일치해야한다(repsonse)
{
"resultcode": "00",
"message": "success",
"response": {
"email": "openapi@naver.com",
"nickname": "OpenAPI",
...
}
}
<RESTful Web Services(Message)>
1. User issues URL from a browser(http://host:port/path/file) -> Client(Browser)
2. Brower sends a 'request message' -> HTTP(Over TCP/IP)
3. Server maps the URL to a file or program under the document directory -> Server(@ host : port)
4. Server returns a 'response message' -> HTTP(Over TCP/IP)
5. Browser formats the response and display -> Client(Browser)
- HTTP request message : ASCII(human-readable format)
- Request line
- Header lines
- Black line
- Entity Body
- An HTTP 'Request' has five major parts:
- Method
- Indicates the HTTP methods such as GET, POST, DELETE, PUT, etc
- URI
- Uniform Resource Identifier (URI) to identify the resource on the server
- HTTP Version
- Indicates the HTTP version. For example, HTTP v1.1
- Request Header
- Contains metadata for the HTTP Request message as key-value pairs. For example, client (or browser) type, format supported by the client, format of the message body, cache settings, etc
- Request Body
- Message content or Resource representation
- An HTTP 'Response' has four major parts:
- Status/Response Code
- Indicates the Server status for the requested resource. For example, 404 means resource not found and 200 means response is OK
- HTTP Version
- Indicates the HTTP version. For example HTTP v1.1
- Response Header
- Contains metadata for the HTTP Response message as key-value pairs. For example, content length, content type, etc.
- Response Body
- Response message content or Resource representation
- Content Negotiation
- Request (client)
- Accept: Give me this kind of response. Here’s a list in order of what I’m hoping you’ll send
- ex) Accpet : text/html, application/xhtaml+xml, application/xml
- Response (server)
- Content-Type: This is the kind of response I’m sending you
- ex) Context-Type : text/html; charset=UTF-8
- HTTP Status/Response Codes
- HTTP is built in with a set of status codes for various types of scenarios:
- 2xx Success (200 OK, 201 Created…)
- 3xx Redirection (303 See other)
- 4xx Client error (404 Not Found)
- 5xx Server error (500 Internal Server Error)
<RESTful Web Services(Addressing)>
- Each resource in REST architecture is identified by its URI (Uniform Resource Identifier)
- A URI is of the following format: //resource는 URI를 통해서 식별이 된다
- ex) URI format
<protocol>://<service-name>/<ResourceType>/<ResourceID>
http://localhost:8080/estore/users/1
- Constructing a Standard URI(URI를 만드는 방법)
- Use Plural Noun //복수형을 사용
- Use plural noun to define resources. For example, we've used users to identify 'users' as a resource
- Avoid using spaces //spaces(%)를 피해라, (-), (_)를 사용
- Use underscore (_) or hyphen (-) when using a long resource name. For example, use authorized_users instead of authorized%20users
- Use lowercase letters //소문자를 사용
- Although URI is case-insensitive, it is a good practice to keep the url in lower case letters only
- Maintain Backward Compatibility //호환성은 유지
- As Web Service is a public service, a URI should always be available. In case URI gets updated, redirect the older URI to a new URI using the HTTP Status code, 300
- Use HTTP Verb : GET, PUT, DELETE
- Always use HTTP Verb like GET, PUT and DELETE to do the operations on the resource. It is not good to use operations name in the URI
- ex)
Following is an example of a 'poor' URI to fetch a user: //사용자 조회 중 바람직하지 못한것
http://localhost:8080/.../getUser/1 -> 복수형 사용x, operation Name은 사용하면 안된다
Following is an example of a 'good' URI to fetch a user: //사용자 조회 중 바람직한 것
http://localhost:8080/.../users/1 -> 복수형 사용o
<RESTful Web Services(Methods)>
- HTTP Method, URI and Operation
1. Get http://localhost:8080/estore/users
GET the list of users //모든 사용자를 조회
2. Get http://localhost:8080/estore/users/1 //1은 id
GET the User of Id 1 //특정 사용자 조회
3. POST http://localhost:8080/estore/users/2
Inserts User with Id 2 //새롭게 생성 또는 사용하는 것(POST, Inserts)
4. PUT http://localhost:8080/estore/users/2
Updates the User with Id 2 //갱신(PUT, Updates)
5. DELETE http://localhost:8080/estore/users/1
Deletes the User with Id 1 //삭제(DELETE, Deletes)
6. OPTIONS http://localhost:8080/estore/users
Lists out the supported operations in a web service //지원되는 operation이 무엇인지 조회
7. HEAD http://localhost:8080/estore/users
Returns the HTTP Header only, on Body //Header정보(HTTP)만 가져온다
<RESTful Web Services(Statelessness)>
- A RESTful Web Service should not keep a client state(session data, preferences) on the server -> A RESTful Web Service는 클라이언트의 data나 preferences(선호)를 저장해서는 안된다
- This restriction is called Statelessness -> 클라이언트의 정보를 저장하지 않는다
- 장점 : 서버부하가 발생하면 Load Balancer가 부하가 일어나지 않게 분배한다
- 'Stateful' components, such as 'authentication' and 'authorization' services //보안관련
1. Session based Authentication //session에 기반하여 인증
2. Token based Authentication //token에 기반하여 인증
<Session-based authentication>
- Stateful authentication technique
- Use sessions to keep track of the authenticated user
- ex)
Client -> Client sends login details{username, password} -> Server
{username, password}는 Server의 메모리 안에 있는 seesion data에 저장된다
Server -> Sends {session_id} to cookies -> Client
Client -> {session_id sent from cookis}, Get user profile(Authenticated request) -> Server
Server는 session_id와 저장된 data안에 있는 session_id와 비교한다
Server -> Sends user profile on success(사용자의 profile을 Client에게 넘긴다) -> Client
*Cookie
- 웹사이트 접속 시 접속자의 개인장치에 다운로드 되고 브라우저에 저장되는 작은 텍스트 파일(작은 정보기록 파일)
- 웹사이트는 쿠키를 통해 접속자의 장치를 인식하고, 접속자의 설정에 과거 이용내역에 대한 일부 데이터를 저장한다. 일반적으로 쿠키에는 만료일이 있다
<Token based authentication>
- Stateless authentication technique
- servers use 'token' authentication to check the identity of a user
- The preferred mode of authentication for RESTful APIs
1. The user data(사용자 정보) is encrypted(암호화) into a JWT(JSON Web Token) with a secret and then sent back to the client
2. The JWT is then stored on the client side and sent as a header for every subsequent request(매번 요청할 때 마다 header정보에 담아 보낸다)
3. The server receives and validates the JWT before proceeding to send a response to the client
- ex)
Client -> Client sends login details {username, password} -> Server
Server에 JWT(JSON Web Token)를 생성한다
Server -> Sends back generated {JWT} to client -> Client(Saves JWT on localstorage)
Client -> Get user profile(Authenicated request) -> Server(Validates JWT(token 검증))
Sets token to header
{
headers:{ //header 정보에 토큰의 cotent를 담아서 보낸다
"Authorization":"Bearer ${JWT_TOKEN}"
}
Server -> Sends user profile on success -> Client
<RESTful Web Services(Statelessness)>
- Advantages of Statelessness(Statelessness의 장점)
- Web services can treat each method request independently //요청을 독립적으로 처리
- Web services need not maintain the client's previous interactions. It simplifies the application design //설계가 단순화
- As HTTP is itself a statelessness protocol, RESTful Web Services work seamlessly with the HTTP protocols //HTTP자체가 statelessness이기 때문에 RESTful Web Services와 호환가능, 확장성o
<RESTful Web Services(Caching)>
- Caching refers to storing the server response(서버에서 응답이 올 때) in the client itself(Client쪽에서 저장을 하는 것), so that a client need not make a server request for the same resource again and again(Client는 동일한 자원을 반복적으로 서버쪽에 요청할 필요가 없다)
- A server response(서버에 응답을 받으면) should have information about how caching is to be done(캐싱이 어떻게 이루어져있는지 정보 제공), so that a client caches the response for a time-period or never caches the server response
- ex) information about how caching is to be done
▼ Response Headers
accpet-ranges : bytes
atl-svc : quic=":443; ma=2592000; v="39,38,37,36,35"
cache-control : public, max-age=31536000 //정보
content-encoding : gzip
content-length : 10718
- ex)
Client Brower -> Is resource cache and not stale*? -> Web Server
Web Server -> No : Request from server -> Client Browser
Client Browser -> Is resource cache and not stale? -> Local Brower Cache
Local Brower Cache -> Yes : Bypass server, fetch from browser cache
*stale : 최신이 아닌 데이터를 반영
Header & Description(server response)
1. Date
- Date and Time of the resource when it was created
2. Last Motified
- Date and Time of resource when it was last motified
3. Cache-Control
- Primary header to control caching
4. Expires
- Expiration data and time of caching
--------------------------------------------------------------------------------
3. Cach-Control(ex. cache-control : public, max-age=31536000) , Header & Description
1. Public
- Indicates that resource is cacheable by any component //누구나 저장 가능(CDN에 저장)
2. Private
- Indicates that resource is cacheable only by the client and the server,
no intermediary(CDN) can cache the resource //client쪽에서만 cache 저장(CDN에 저장x)
*Client - CDN - Server
*CDN : Content Delivery Network
3. no-store
- Indicateds that resource is not cacheable //저장할 수 없다, CDN에도 저장x
4. max-age
- Indicates the caching is vaild up to max-age in seconds //유효기한(단위는 초 단위)
5. must-revalidate
- Indicates that the response can be reused while fresh. If the response becomes stale,
it must be validated with the origin server before reuse //만료되지 않았을 때는 재사용이 가능하지만, 만료되었다면 검증이 이루어진다
“no-store” //not Reusable Resource
- it disallows browsers and all intermediate caches from storing any versions of returned responses. used for sensitive data, such as personal banking details.
“no-cache”
- web browsers might cache the resources but they have to check on every request if the resources have changed(모든 요청에서 resource가 변경되었는지 체크해야한다)
“max-age” //초 단위로 유효기간 표시, 지나게 되면 새로운 버전을 요청
- max-age=120 means that the returned resource is valid for 120 seconds, after which the browser has to request a newer version
- Always keep 'static contents' like images, CSS, JavaScript cacheable, with expiration date of 2 to 3 days
- 'Dynamic content' should be cached for a few hours only
- When using the "Cache-Control: no-cache" header,
clients must always request revalidation(재검증), typically using the "If-None-Match" header (ETag value)
- The web server will return the resource's current representation along with its corresponding 'ETag' value(validation token).
- An ETag is an identifier assigned by a web server to a 'specific version of a resource' found at a URL.
If the resource representation at that URL ever changes, a new and different ETag is assigned.
- If the client wants to retrieve the same URL resource again,
it will first determine whether the local cached version of the URL has expired(캐쉬에 저장된 resource의 유효기간이 지났는지 판단한다)
- If the URL has not expired, it will retrieve the local cached resource. //유효기간이 지나지 않았다면 Resource cache를 rendering해서 그대로 사용
- If it is determined that the URL has expired (stale), then the client will contact the server and send its previously saved copy of the ETag along with the request in a "If-None-Match" field
- The server may now compare the client's ETag with the ETag for the current version of the resource
- If the ETag values match, meaning that the resource has not changed, then the server may send back a very short response with a HTTP 304 Not Modified status. (The 304 status tells the client that its cached version is still good and that it should use that)
//유효기간이 지났다면 Client는 GET/file과 "If-Non-Match"를 전달 즉, Server의 Resource가 변경되었는지 아닌지 체크하고 Server는 Client에서 받은 version과 Server가 가지고 있는 version을 비교한다
일치하면 resource가 변경되지 않았고 서버가 "HTTP 304 Not Modified"을 응답한다
일치하지 않으면 resource가 변경되었고 새로운 content를 rendering해준다
*Etag는 클라이언트(ex. 모바일 디바이스, 웹 브라우저 등)가 이전에 요청했던 데이터와 최신 데이터의 변경사항 유무를 검증하는 데 사용하는 HTTP 응답 헤더입니다.
클라이언트에서 최신 데이터 자료를 요청할 때(HTTP Get 요청) 응답 헤더로 Etag 값이 반환됩니다
<RESTful Web Services(Security)>
The best practices to be adhered to while designing a RESTful Web Service:
- Validation(검증)
- Validate all inputs on the server. Protect your server against SQL injection attacks
- No Sensitive Data in the URL //URL에 sensitive한 데이터를 전송하지 않는다
- Never use username, password or session token in a URL, these values should be passed to Web Service via the 'POST method -> 'Body부분에 담기게 되고 body부분을 암호화 하는 작업 필요'
- Restriction on Method Execution
- limiting specific HTTP methods for certain URLs(ex. POST, GET, DELETE, PUT, OPTIONS, HEAD). It is possible to disallow or restrict PUT and DELETE methods for specific URLs
- Throw generic Error Messages
- A web service method should use 'HTTP error messages' like 403 to show access forbidden, etc.
'웹프레임워크' 카테고리의 다른 글
RestAPI와 예외상황 처리 (0) | 2024.05.08 |
---|---|
JPA (0) | 2024.04.23 |
Spring Security (0) | 2024.04.23 |