유다시티 fullstack 수업 study note입니다
API?
Application Programming Interface. An API is an interface.
Internet Protocols(IPs)
Internet Protocol (IP) is the protocol for sending data from one computer to another across the internet. Each computer must have a unique IP address that identifies it from all other computers connected to the internet. It's likely that you've heard the term IP address before, even if you didn't know exactly what it meant.
There are many other internet protocols including:
- Transmission Control Protocol (TCP) which is used for data transmission
- Hypertext Transmission Protocol (HTTP) which is used for transmitting text and hyperlinks
- File Transfer Protocol (FTP) which is used to transfer files between server and client
*내가 배운건 http프로토콜, 향후에는 tcp, ftp공부도 해봐야할듯.
*IP adress라는 것은 결국 인터넷프로토콜주소
**Restful APIs
REST stands for Representational State Transfer, which is an architectural style
- Uniform Interface: Every rest architecture must have a standardized way of accessing and processing data resources. This include unique resource identifiers (i.e., unique URLs) and self-descriptive messages in the server response that describe how to process the representation (for instance JSON vs XML) of the data resource.
- Stateless: Every client request is self-contained in that the server doesn't need to store any application data in order to make subsequent requests
- Client-Server: There must be both a client and server in the architecture
- Cacheable & Layered System: Caching and layering increases networking efficiency
uniform 주고받는 통신 resource가 스스로 설명되어 있고, 규격화가 되어 있어야함.
stateless 주고받는 리퀘스트가 다음 리퀘스트와 상관없이 별도의 standalone이어야함
client-server 클라이언트 서버 가 주체가 되는 아키테쳐 스타일
stateless 지만 캐쉬나 레이여를 이용해서 효율적인 통신 가능
HTTP
- Connectionless: When a request is sent, the client opens the connection; once a response is received, the client closes the connection. The client and server only maintain a connection during the response and request. Future responses are made on a new connection. (커넥션이 없을때는 포트를 비워둔다는 이야기)
- Stateless: There is no dependency between successive requests.
- Not Sessionless: Utilizing headers and cookies, sessions can be created to allow each HTTP request to share the same context. (각각의 리퀘스트는 stateless 하지만 쿠키 등을 이용하여 세쎤으로 엮인다)
- Media Independent: Any type of data can be sent over HTTP as long as both the client and server know how to handle the data format. In our case, we'll use JSON.
Elements of HTTP
- URI
- Messages (request and response)
- Status code (e.g 404 not found)
URI components:
- Scheme: specifies the protocol used to access the resource, HTTP or HTTPS. In our example http.
- Host: specifies the host that holds the resources. In our example www.example.com.
- Path: specifies the specific resource being requested. In our example, /tasks.
- Query: an optional component, the query string provides information the resource can use for some purpose such as a search parameter. In our example, /term=homework.
HTTP REQUEST AND RESPONSE
REQUEST Elements:
- Method: Defines the operation to be performed
-
Path: The URL of the resource to be fetched, excluding the scheme and host
-
HTTP Version
-
Headers: optional information, success as Accept-Language
-
Body: optional information, usually for methods such as POST and PATCH, which contain the resource being sent to the server
Request Methods
Different request methods indicate different operations to be performed. It's essential to attend to this to correctly format your requests and properly structure an API.
-
GET: ONLY retrieves information for the requested resource of the given URI
-
POST: Send data to the server to create a new resource.
-
PUT: Replaces all of the representation of the target resource with the request data
-
PATCH: Partially modifies the representation of the target resource with the request data
-
DELETE: Removes all of the representation of the resource specified by the URI
-
OPTIONS: Sends the communication options for the requested resource
RESPONSE Elements:
-
Status Code & Status Message
-
HTTP Version
-
Headers: similar to the request headers, provides information about the response and resource representation. Some common headers include:
-
Date
-
Content-Type: the media type of the body of the response
-
-
Body: optional data containing the requested resource
configure 옵션에 대해서도 약간 다루는데 이 부분은 필요할때 해당 docu를 참고해볼것 (스크린샷도 남겨놓음)
Chrome devtool and Curl
기능을 잘 숙지하면 테스팅하는데 유용, 익숙할때까지 자주 사용할 것
CORS
CORS stands for "cross origin resource sharing"
The same-origin policy is a concept of web security that allows scripts in Webpage 1 to access data from Webpage 2 only if they share the same domain. This means that the above error will be raised in the following cases:
- Different domains
- Different subdomains (example.com and api.example.com)
- Different ports (example.com and example.com:1234)
- Different protocols (http://example.com and https://example.com)
If you're sending any requests beyond very simple GET or POST requests, then before your actual request is sent, the browser sends a preflight OPTIONS request to the server. If CORS is not enabled, then the browser will not respond properly and the actual request will not be sent.
preflight request에 response가 cors header를 포함하지 않고 있다면, 브라우저는 main request를 보낼수 없음.
CORS header에는 4가지 종류가 있다.
-
Access-Control-Allow-Origin / What client domains can access its resources. For any domain use *
-
Access-Control-Allow-Credentials / Only if using cookies for authentication - in which case its value must be true
-
Access-Control-Allow-Methods / List of HTTP request types allowed
-
Access-Control-Allow-Headers / List of http request header values the server will allow, particularly useful if you use any custom headers
FLASK-CORS
pip install flask-cors /or pip3 install flask-cors
사용방법에는 크게 3가지가 있는데,
1) 우선 CORS(app)을 통해 app에 cors를 적용시켜줘야 한다.
이때 resources라는 파라미터를 이용해서 cors policy를 적용할수 있다.
cors = CORS(app, resources={r"/api/*": {"origins": "*"}})
2) CORS 앱을 적용해줬다면,
@app.after_request라는 데코레이터를 이용해서
response header에 코스헤더를 커스텀해서 덧붙여줄수있다.
해당 데코레이터는 모든 리스판스에 적용되므로, preflight request가 왔을때 대응하는 리스판스에도 적용될것.
3)아니면 특정 app.route 데코레이터 아래에
@cross_origin 데코레이터를 붙일수있다.
이 경우 해당 url에는 cors가 적용된다.
ERROR HANDLING
FLASK에는 기본적으로 abort function이 있지만
이는 html의 형태의 에러 메시지만을 보낸다.
커스터마이징을 위해서
@app.errorhandler() 데코레이터를 활용할수있다.
TESTING
The order of app development
- Development
- Unit Testing
- Quality Assurance
- Production
Unittest setup & syntax
SETUP 시 테스트용으로 별도로 데이터베이스를 만들어주는 것이 좋다.
프로덕션용 데이터베이스 건들지 않을것.
**기본 setup에 관한 구체적인 코드는 강의 동영상 참고할것. (+ trivia project)
기본적으로 test instance에 대해서 세팅하는 내용이고, 수행할 테스트에 관련된 코드가 들어가게 됨
TDD
-test driven development로서 중요한 개념
안정적인 개발 cycle로서 아래와 같은 단계를 거친다.
- Write test for specific application behavior.
- Run the tests and watch them fail.
- Write code to execute the required behavior.
- Test the code and rewrite as necessary to pass the test
- Refactor your code.
- Repeat - write your next test.
API Documentation
-누구든지 api 다큐를 보고 api구조와 각각 end point 기능을 쉽게 이해할수 있어야 한다.
(google maps api 나 stripe api 정도 참고)
아래 정도 목차면 best practice라고 할수 있다.
- Introduction
- Getting Started
- Base URL
- API Keys /Authentication (if applicable)
- Errors
- Response codes
- Messages
- Error types
- Resource endpoint library
- Organized by resource
- Include each endpoint
- Sample request
- Arguments including data types
- Response object including status codes and data types
'백엔드 > 유다시티수업' 카테고리의 다른 글
4.2 kubernetes, AWS, EKS (0) | 2021.01.12 |
---|---|
4.1 Docker, containerization (0) | 2021.01.09 |
3. Identity and Access Management (0) | 2020.12.27 |
1. SQL & Data Modeling (0) | 2020.12.14 |