Hướng dẫn what is rest api example python? - Phần còn lại api ví dụ python là gì?

Có một lượng dữ liệu đáng kinh ngạc có sẵn trên web. Nhiều dịch vụ web, như YouTube và GitHub, giúp dữ liệu của họ có thể truy cập được vào các ứng dụng của bên thứ ba thông qua giao diện lập trình ứng dụng (API). Một trong những cách phổ biến nhất để xây dựng API là phong cách kiến ​​trúc còn lại. Python cung cấp một số công cụ tuyệt vời không chỉ để lấy dữ liệu từ các API REST mà còn để xây dựng API REST Python của riêng bạn.web services, like YouTube and GitHub, make their data accessible to third-party applications through an application programming interface (API). One of the most popular ways to build APIs is the REST architecture style. Python provides some great tools not only to get data from REST APIs but also to build your own Python REST APIs.

Show

Trong hướng dẫn này, bạn sẽ học:

  • Kiến trúc nghỉ ngơi là gìREST architecture is
  • Cách các API REST cung cấp quyền truy cập vào dữ liệu webREST APIs provide access to web data
  • Cách sử dụng dữ liệu từ API REST bằng thư viện
    >>> import requests
    >>> api_url = "https://jsonplaceholder.typicode.com/todos/10"
    >>> response = requests.get(api_url)
    >>> response.json()
    {'userId': 1, 'id': 10, 'title': 'illo est ... aut', 'completed': True}
    
    >>> todo = {"userId": 1, "title": "Wash car", "completed": True}
    >>> response = requests.put(api_url, json=todo)
    >>> response.json()
    {'userId': 1, 'title': 'Wash car', 'completed': True, 'id': 10}
    
    >>> response.status_code
    200
    
    2
    >>> import requests
    >>> api_url = "https://jsonplaceholder.typicode.com/todos/10"
    >>> response = requests.get(api_url)
    >>> response.json()
    {'userId': 1, 'id': 10, 'title': 'illo est ... aut', 'completed': True}
    
    >>> todo = {"userId": 1, "title": "Wash car", "completed": True}
    >>> response = requests.put(api_url, json=todo)
    >>> response.json()
    {'userId': 1, 'title': 'Wash car', 'completed': True, 'id': 10}
    
    >>> response.status_code
    200
    
    2
    library
  • Những bước nào cần thực hiện để xây dựng API RESTbuild a REST API
  • Một số công cụ Python phổ biến là gì để xây dựng API RESTPython tools are for building REST APIs

Bằng cách sử dụng API Python và REST, bạn có thể truy xuất, phân tích, cập nhật và thao tác dữ liệu được cung cấp bởi bất kỳ dịch vụ web nào mà bạn quan tâm.

Kiến trúc nghỉ ngơi

REST là viết tắt của chuyển giao trạng thái đại diện và là phong cách kiến ​​trúc phần mềm xác định một mẫu cho giao tiếp máy khách và máy chủ qua mạng. REST cung cấp một tập hợp các ràng buộc cho kiến ​​trúc phần mềm để thúc đẩy hiệu suất, khả năng mở rộng, đơn giản và độ tin cậy trong hệ thống. stands for representational state transfer and is a software architecture style that defines a pattern for client and server communications over a network. REST provides a set of constraints for software architecture to promote performance, scalability, simplicity, and reliability in the system.

REST xác định các ràng buộc kiến ​​trúc sau:

  • Không quốc tịch: Máy chủ giành được duy trì bất kỳ trạng thái nào giữa các yêu cầu từ máy khách. The server won’t maintain any state between requests from the client.
  • Máy khách-máy chủ: Máy khách và máy chủ phải được tách rời nhau, cho phép mỗi người phát triển độc lập. The client and server must be decoupled from each other, allowing each to develop independently.
  • Có thể lưu trữ: Dữ liệu được lấy từ máy chủ phải được lưu trữ bởi máy khách hoặc máy chủ. The data retrieved from the server should be cacheable either by the client or by the server.
  • Giao diện thống nhất: Máy chủ sẽ cung cấp giao diện thống nhất để truy cập tài nguyên mà không cần xác định đại diện của chúng. The server will provide a uniform interface for accessing resources without defining their representation.
  • Hệ thống xếp lớp: Máy khách có thể truy cập các tài nguyên trên máy chủ một cách gián tiếp thông qua các lớp khác như proxy hoặc cân bằng tải. The client may access the resources on the server indirectly through other layers such as a proxy or load balancer.
  • Mã theo yêu cầu (tùy chọn): Máy chủ có thể chuyển mã cho máy khách mà nó có thể chạy, chẳng hạn như JavaScript cho một ứng dụng một trang. The server may transfer code to the client that it can run, such as JavaScript for a single-page application.

Lưu ý, REST không phải là một đặc điểm kỹ thuật mà là một bộ hướng dẫn về cách kiến ​​trúc sư một hệ thống phần mềm kết nối mạng.

API nghỉ ngơi và dịch vụ web

Dịch vụ web REST là bất kỳ dịch vụ web nào tuân thủ các ràng buộc kiến ​​trúc REST. Các dịch vụ web này đưa dữ liệu của họ ra thế giới bên ngoài thông qua API. API REST cung cấp quyền truy cập vào dữ liệu dịch vụ web thông qua các URL web công cộng.REST web service is any web service that adheres to REST architecture constraints. These web services expose their data to the outside world through an API. REST APIs provide access to web service data through public web URLs.

Ví dụ, ở đây, một trong những URL cho API REST GitHub:

https://api.github.com/users/

URL này cho phép bạn truy cập thông tin về một người dùng GitHub cụ thể. Bạn truy cập dữ liệu từ API REST bằng cách gửi yêu cầu HTTP đến URL cụ thể và xử lý phản hồi.

Phương pháp HTTP

REST API lắng nghe các phương thức HTTP như

>>> import requests
>>> api_url = "https://jsonplaceholder.typicode.com/todos/10"
>>> response = requests.get(api_url)
>>> response.json()
{'userId': 1, 'id': 10, 'title': 'illo est ... aut', 'completed': True}

>>> todo = {"userId": 1, "title": "Wash car", "completed": True}
>>> response = requests.put(api_url, json=todo)
>>> response.json()
{'userId': 1, 'title': 'Wash car', 'completed': True, 'id': 10}

>>> response.status_code
200
3,
>>> import requests
>>> api_url = "https://jsonplaceholder.typicode.com/todos/10"
>>> response = requests.get(api_url)
>>> response.json()
{'userId': 1, 'id': 10, 'title': 'illo est ... aut', 'completed': True}

>>> todo = {"userId": 1, "title": "Wash car", "completed": True}
>>> response = requests.put(api_url, json=todo)
>>> response.json()
{'userId': 1, 'title': 'Wash car', 'completed': True, 'id': 10}

>>> response.status_code
200
4 và
>>> import requests
>>> api_url = "https://jsonplaceholder.typicode.com/todos/10"
>>> response = requests.get(api_url)
>>> response.json()
{'userId': 1, 'id': 10, 'title': 'illo est ... aut', 'completed': True}

>>> todo = {"userId": 1, "title": "Wash car", "completed": True}
>>> response = requests.put(api_url, json=todo)
>>> response.json()
{'userId': 1, 'title': 'Wash car', 'completed': True, 'id': 10}

>>> response.status_code
200
5 để biết hoạt động nào sẽ thực hiện trên tài nguyên dịch vụ web. Tài nguyên là bất kỳ dữ liệu nào có sẵn trong dịch vụ web có thể được truy cập và thao tác với các yêu cầu HTTP cho API REST. Phương thức HTTP cho API biết hành động nào sẽ thực hiện trên tài nguyên.resource is any data available in the web service that can be accessed and manipulated with HTTP requests to the REST API. The HTTP method tells the API which action to perform on the resource.

Mặc dù có nhiều phương thức HTTP, năm phương thức được liệt kê dưới đây là các phương thức được sử dụng phổ biến nhất với API REST:

Phương pháp HTTPSự mô tả
>>> import requests
>>> api_url = "https://jsonplaceholder.typicode.com/todos/10"
>>> response = requests.get(api_url)
>>> response.json()
{'userId': 1, 'id': 10, 'title': 'illo est ... aut', 'completed': True}

>>> todo = {"userId": 1, "title": "Wash car", "completed": True}
>>> response = requests.put(api_url, json=todo)
>>> response.json()
{'userId': 1, 'title': 'Wash car', 'completed': True, 'id': 10}

>>> response.status_code
200
3
Lấy một tài nguyên hiện có.
>>> import requests
>>> api_url = "https://jsonplaceholder.typicode.com/todos/10"
>>> response = requests.get(api_url)
>>> response.json()
{'userId': 1, 'id': 10, 'title': 'illo est ... aut', 'completed': True}

>>> todo = {"userId": 1, "title": "Wash car", "completed": True}
>>> response = requests.put(api_url, json=todo)
>>> response.json()
{'userId': 1, 'title': 'Wash car', 'completed': True, 'id': 10}

>>> response.status_code
200
4
Tạo một tài nguyên mới.
>>> import requests
>>> api_url = "https://jsonplaceholder.typicode.com/todos/10"
>>> response = requests.get(api_url)
>>> response.json()
{'userId': 1, 'id': 10, 'title': 'illo est ... aut', 'completed': True}

>>> todo = {"userId": 1, "title": "Wash car", "completed": True}
>>> response = requests.put(api_url, json=todo)
>>> response.json()
{'userId': 1, 'title': 'Wash car', 'completed': True, 'id': 10}

>>> response.status_code
200
8
Cập nhật một tài nguyên hiện có.
>>> import requests
>>> api_url = "https://jsonplaceholder.typicode.com/todos/10"
>>> response = requests.get(api_url)
>>> response.json()
{'userId': 1, 'id': 10, 'title': 'illo est ... aut', 'completed': True}

>>> todo = {"userId": 1, "title": "Wash car", "completed": True}
>>> response = requests.put(api_url, json=todo)
>>> response.json()
{'userId': 1, 'title': 'Wash car', 'completed': True, 'id': 10}

>>> response.status_code
200
9
Cập nhật một phần một tài nguyên hiện có.
>>> import requests
>>> api_url = "https://jsonplaceholder.typicode.com/todos/10"
>>> response = requests.get(api_url)
>>> response.json()
{'userId': 1, 'id': 10, 'title': 'illo est ... aut', 'completed': True}

>>> todo = {"userId": 1, "title": "Wash car", "completed": True}
>>> response = requests.put(api_url, json=todo)
>>> response.json()
{'userId': 1, 'title': 'Wash car', 'completed': True, 'id': 10}

>>> response.status_code
200
5
Xóa một tài nguyên.

Ứng dụng máy khách API REST có thể sử dụng năm phương thức HTTP này để quản lý trạng thái tài nguyên trong dịch vụ web.

Mã trạng thái

Khi API REST nhận và xử lý yêu cầu HTTP, nó sẽ trả về phản hồi HTTP. Bao gồm trong phản hồi này là mã trạng thái HTTP. Mã này cung cấp thông tin về kết quả của yêu cầu. Một ứng dụng gửi các yêu cầu đến API có thể kiểm tra mã trạng thái và thực hiện các hành động dựa trên kết quả. Những hành động này có thể bao gồm xử lý lỗi hoặc hiển thị thông báo thành công cho người dùng.HTTP response. Included in this response is an HTTP status code. This code provides information about the results of the request. An application sending requests to the API can check the status code and perform actions based on the result. These actions could include handling errors or displaying a success message to a user.

Dưới đây là danh sách các mã trạng thái phổ biến nhất được trả về bởi API REST:

Mã sốNghĩaSự mô tả
>>> import requests
>>> api_url = "https://jsonplaceholder.typicode.com/todos/10"
>>> response = requests.get(api_url)
>>> response.json()
{'userId': 1, 'id': 10, 'title': 'illo est ... aut', 'completed': True}

>>> todo = {"userId": 1, "title": "Wash car", "completed": True}
>>> response = requests.put(api_url, json=todo)
>>> response.json()
{'userId': 1, 'title': 'Wash car', 'completed': True, 'id': 10}

>>> response.status_code
200
3
Lấy một tài nguyên hiện có.
>>> import requests
>>> api_url = "https://jsonplaceholder.typicode.com/todos/10"
>>> response = requests.get(api_url)
>>> response.json()
{'userId': 1, 'id': 10, 'title': 'illo est ... aut', 'completed': True}

>>> todo = {"userId": 1, "title": "Wash car", "completed": True}
>>> response = requests.put(api_url, json=todo)
>>> response.json()
{'userId': 1, 'title': 'Wash car', 'completed': True, 'id': 10}

>>> response.status_code
200
4
Tạo một tài nguyên mới.
>>> import requests
>>> api_url = "https://jsonplaceholder.typicode.com/todos/10"
>>> response = requests.get(api_url)
>>> response.json()
{'userId': 1, 'id': 10, 'title': 'illo est ... aut', 'completed': True}

>>> todo = {"userId": 1, "title": "Wash car", "completed": True}
>>> response = requests.put(api_url, json=todo)
>>> response.json()
{'userId': 1, 'title': 'Wash car', 'completed': True, 'id': 10}

>>> response.status_code
200
8
Cập nhật một tài nguyên hiện có.
>>> import requests
>>> api_url = "https://jsonplaceholder.typicode.com/todos/10"
>>> response = requests.get(api_url)
>>> response.json()
{'userId': 1, 'id': 10, 'title': 'illo est ... aut', 'completed': True}

>>> todo = {"userId": 1, "title": "Wash car", "completed": True}
>>> response = requests.put(api_url, json=todo)
>>> response.json()
{'userId': 1, 'title': 'Wash car', 'completed': True, 'id': 10}

>>> response.status_code
200
9
Cập nhật một phần một tài nguyên hiện có.
>>> import requests
>>> api_url = "https://jsonplaceholder.typicode.com/todos/10"
>>> response = requests.get(api_url)
>>> response.json()
{'userId': 1, 'id': 10, 'title': 'illo est ... aut', 'completed': True}

>>> todo = {"userId": 1, "title": "Wash car", "completed": True}
>>> response = requests.put(api_url, json=todo)
>>> response.json()
{'userId': 1, 'title': 'Wash car', 'completed': True, 'id': 10}

>>> response.status_code
200
5
Xóa một tài nguyên.Ứng dụng máy khách API REST có thể sử dụng năm phương thức HTTP này để quản lý trạng thái tài nguyên trong dịch vụ web.Mã trạng thái
Khi API REST nhận và xử lý yêu cầu HTTP, nó sẽ trả về phản hồi HTTP. Bao gồm trong phản hồi này là mã trạng thái HTTP. Mã này cung cấp thông tin về kết quả của yêu cầu. Một ứng dụng gửi các yêu cầu đến API có thể kiểm tra mã trạng thái và thực hiện các hành động dựa trên kết quả. Những hành động này có thể bao gồm xử lý lỗi hoặc hiển thị thông báo thành công cho người dùng.Dưới đây là danh sách các mã trạng thái phổ biến nhất được trả về bởi API REST:Mã số
Nghĩa
{'userId': 1, 'title': 'Wash car', 'completed': True, 'id': 10}
1
ĐƯỢC RỒI
Các hành động được yêu cầu đã thành công.
{'userId': 1, 'title': 'Wash car', 'completed': True, 'id': 10}
2
Tạo
Một tài nguyên mới đã được tạo ra.
{'userId': 1, 'title': 'Wash car', 'completed': True, 'id': 10}
3
Đã được chấp nhận
Yêu cầu đã được nhận, nhưng chưa có sửa đổi nào được thực hiện.
{'userId': 1, 'title': 'Wash car', 'completed': True, 'id': 10}
4
Không có nội dung
Yêu cầu đã thành công, nhưng phản hồi không có nội dung.
{'userId': 1, 'title': 'Wash car', 'completed': True, 'id': 10}
5
Yêu cầu xấu

Mười mã trạng thái này chỉ đại diện cho một tập hợp con nhỏ của mã trạng thái HTTP có sẵn. Mã trạng thái được đánh số dựa trên danh mục kết quả:

Phạm vi mãLoại
>>> import requests
>>> api_url = "https://jsonplaceholder.typicode.com/todos/10"
>>> todo = {"title": "Mow lawn"}
>>> response = requests.patch(api_url, json=todo)
>>> response.json()
{'userId': 1, 'id': 10, 'title': 'Mow lawn', 'completed': True}

>>> response.status_code
200
1
Hoạt động thành công
>>> import requests
>>> api_url = "https://jsonplaceholder.typicode.com/todos/10"
>>> todo = {"title": "Mow lawn"}
>>> response = requests.patch(api_url, json=todo)
>>> response.json()
{'userId': 1, 'id': 10, 'title': 'Mow lawn', 'completed': True}

>>> response.status_code
200
2
Chuyển hướng
>>> import requests
>>> api_url = "https://jsonplaceholder.typicode.com/todos/10"
>>> todo = {"title": "Mow lawn"}
>>> response = requests.patch(api_url, json=todo)
>>> response.json()
{'userId': 1, 'id': 10, 'title': 'Mow lawn', 'completed': True}

>>> response.status_code
200
3
Lỗi máy khách
>>> import requests
>>> api_url = "https://jsonplaceholder.typicode.com/todos/10"
>>> todo = {"title": "Mow lawn"}
>>> response = requests.patch(api_url, json=todo)
>>> response.json()
{'userId': 1, 'id': 10, 'title': 'Mow lawn', 'completed': True}

>>> response.status_code
200
4
Lỗi máy chủ

Mã trạng thái HTTP có ích khi làm việc với API REST vì bạn thường cần thực hiện logic khác nhau dựa trên kết quả của yêu cầu.

Điểm cuối API

API REST phơi bày một tập hợp các URL công khai mà các ứng dụng khách hàng sử dụng để truy cập các tài nguyên của dịch vụ web. Các URL này, trong bối cảnh của API, được gọi là điểm cuối.endpoints.

Để giúp làm rõ điều này, hãy xem bảng dưới đây. Trong bảng này, bạn sẽ thấy các điểm cuối API cho một hệ thống CRM giả thuyết. Các điểm cuối này dành cho tài nguyên khách hàng đại diện cho tiềm năng

>>> import requests
>>> api_url = "https://jsonplaceholder.typicode.com/todos/10"
>>> todo = {"title": "Mow lawn"}
>>> response = requests.patch(api_url, json=todo)
>>> response.json()
{'userId': 1, 'id': 10, 'title': 'Mow lawn', 'completed': True}

>>> response.status_code
200
5 trong hệ thống:

Phương pháp HTTPĐiểm cuối APISự mô tả
>>> import requests
>>> api_url = "https://jsonplaceholder.typicode.com/todos/10"
>>> response = requests.get(api_url)
>>> response.json()
{'userId': 1, 'id': 10, 'title': 'illo est ... aut', 'completed': True}

>>> todo = {"userId": 1, "title": "Wash car", "completed": True}
>>> response = requests.put(api_url, json=todo)
>>> response.json()
{'userId': 1, 'title': 'Wash car', 'completed': True, 'id': 10}

>>> response.status_code
200
3
>>> import requests
>>> api_url = "https://jsonplaceholder.typicode.com/todos/10"
>>> todo = {"title": "Mow lawn"}
>>> response = requests.patch(api_url, json=todo)
>>> response.json()
{'userId': 1, 'id': 10, 'title': 'Mow lawn', 'completed': True}

>>> response.status_code
200
7
Nhận một danh sách các khách hàng.
>>> import requests
>>> api_url = "https://jsonplaceholder.typicode.com/todos/10"
>>> response = requests.get(api_url)
>>> response.json()
{'userId': 1, 'id': 10, 'title': 'illo est ... aut', 'completed': True}

>>> todo = {"userId": 1, "title": "Wash car", "completed": True}
>>> response = requests.put(api_url, json=todo)
>>> response.json()
{'userId': 1, 'title': 'Wash car', 'completed': True, 'id': 10}

>>> response.status_code
200
3
>>> import requests
>>> api_url = "https://jsonplaceholder.typicode.com/todos/10"
>>> todo = {"title": "Mow lawn"}
>>> response = requests.patch(api_url, json=todo)
>>> response.json()
{'userId': 1, 'id': 10, 'title': 'Mow lawn', 'completed': True}

>>> response.status_code
200
7
Nhận một danh sách các khách hàng.
>>> import requests
>>> api_url = "https://jsonplaceholder.typicode.com/todos/10"
>>> todo = {"title": "Mow lawn"}
>>> response = requests.patch(api_url, json=todo)
>>> response.json()
{'userId': 1, 'id': 10, 'title': 'Mow lawn', 'completed': True}

>>> response.status_code
200
9
>>> import requests
>>> api_url = "https://jsonplaceholder.typicode.com/todos/10"
>>> todo = {"title": "Mow lawn"}
>>> response = requests.patch(api_url, json=todo)
>>> response.json()
{'userId': 1, 'id': 10, 'title': 'Mow lawn', 'completed': True}

>>> response.status_code
200
7
Nhận một danh sách các khách hàng.
>>> import requests
>>> api_url = "https://jsonplaceholder.typicode.com/todos/10"
>>> todo = {"title": "Mow lawn"}
>>> response = requests.patch(api_url, json=todo)
>>> response.json()
{'userId': 1, 'id': 10, 'title': 'Mow lawn', 'completed': True}

>>> response.status_code
200
9
>>> import requests
>>> api_url = "https://jsonplaceholder.typicode.com/todos/10"
>>> todo = {"title": "Mow lawn"}
>>> response = requests.patch(api_url, json=todo)
>>> response.json()
{'userId': 1, 'id': 10, 'title': 'Mow lawn', 'completed': True}

>>> response.status_code
200
7
Nhận một danh sách các khách hàng.
>>> import requests
>>> api_url = "https://jsonplaceholder.typicode.com/todos/10"
>>> todo = {"title": "Mow lawn"}
>>> response = requests.patch(api_url, json=todo)
>>> response.json()
{'userId': 1, 'id': 10, 'title': 'Mow lawn', 'completed': True}

>>> response.status_code
200
9
>>> import requests
>>> api_url = "https://jsonplaceholder.typicode.com/todos/10"
>>> todo = {"title": "Mow lawn"}
>>> response = requests.patch(api_url, json=todo)
>>> response.json()
{'userId': 1, 'id': 10, 'title': 'Mow lawn', 'completed': True}

>>> response.status_code
200
7
Nhận một danh sách các khách hàng.
>>> import requests
>>> api_url = "https://jsonplaceholder.typicode.com/todos/10"
>>> todo = {"title": "Mow lawn"}
>>> response = requests.patch(api_url, json=todo)
>>> response.json()
{'userId': 1, 'id': 10, 'title': 'Mow lawn', 'completed': True}

>>> response.status_code
200
9
>>> import requests
>>> api_url = "https://jsonplaceholder.typicode.com/todos/10"
>>> todo = {"title": "Mow lawn"}
>>> response = requests.patch(api_url, json=todo)
>>> response.json()
{'userId': 1, 'id': 10, 'title': 'Mow lawn', 'completed': True}

>>> response.status_code
200
7
Nhận một danh sách các khách hàng.

>>> import requests
>>> api_url = "https://jsonplaceholder.typicode.com/todos/10"
>>> todo = {"title": "Mow lawn"}
>>> response = requests.patch(api_url, json=todo)
>>> response.json()
{'userId': 1, 'id': 10, 'title': 'Mow lawn', 'completed': True}

>>> response.status_code
200
9

Nhận một khách hàng duy nhất.

>>> import requests
>>> api_url = "https://jsonplaceholder.typicode.com/todos/10"
>>> response = requests.get(api_url)
>>> response.json()
{'userId': 1, 'id': 10, 'title': 'illo est ... aut', 'completed': True}

>>> todo = {"userId": 1, "title": "Wash car", "completed": True}
>>> response = requests.put(api_url, json=todo)
>>> response.json()
{'userId': 1, 'title': 'Wash car', 'completed': True, 'id': 10}

>>> response.status_code
200
4

Tạo một khách hàng mới.

>>> import requests
>>> api_url = "https://jsonplaceholder.typicode.com/todos/10"
>>> response = requests.get(api_url)
>>> response.json()
{'userId': 1, 'id': 10, 'title': 'illo est ... aut', 'completed': True}

>>> todo = {"userId": 1, "title": "Wash car", "completed": True}
>>> response = requests.put(api_url, json=todo)
>>> response.json()
{'userId': 1, 'title': 'Wash car', 'completed': True, 'id': 10}

>>> response.status_code
200
8

Cập nhật một khách hàng.

$ python -m pip install requests

>>> import requests
>>> api_url = "https://jsonplaceholder.typicode.com/todos/10"
>>> response = requests.get(api_url)
>>> response.json()
{'userId': 1, 'id': 10, 'title': 'illo est ... aut', 'completed': True}

>>> todo = {"userId": 1, "title": "Wash car", "completed": True}
>>> response = requests.put(api_url, json=todo)
>>> response.json()
{'userId': 1, 'title': 'Wash car', 'completed': True, 'id': 10}

>>> response.status_code
200
9

Cập nhật một phần một khách hàng.

>>> import requests
>>> api_url = "https://jsonplaceholder.typicode.com/todos/10"
>>> response = requests.get(api_url)
>>> response.json()
{'userId': 1, 'id': 10, 'title': 'illo est ... aut', 'completed': True}

>>> todo = {"userId": 1, "title": "Wash car", "completed": True}
>>> response = requests.put(api_url, json=todo)
>>> response.json()
{'userId': 1, 'title': 'Wash car', 'completed': True, 'id': 10}

>>> response.status_code
200
5read-only operation, so you shouldn’t use it to modify an existing resource.

Xóa một khách hàng.

Mỗi điểm cuối ở trên thực hiện một hành động khác nhau dựa trên phương thức HTTP.

Bạn sẽ lưu ý rằng một số điểm cuối có

$ python -m pip install requests
08 ở cuối. Ký hiệu này có nghĩa là bạn cần nối một số
$ python -m pip install requests
09 vào URL để nói với API còn lại mà
$ python -m pip install requests
10 bạn muốn làm việc cùng.

>>> import requests
>>> api_url = "https://jsonplaceholder.typicode.com/todos/1"
>>> response = requests.get(api_url)
>>> response.json()
{'userId': 1, 'id': 1, 'title': 'delectus aut autem', 'completed': False}

Các điểm cuối được liệt kê ở trên chỉ đại diện cho một tài nguyên trong hệ thống. API REST sẵn sàng sản xuất thường có hàng chục hoặc thậm chí hàng trăm điểm cuối khác nhau để quản lý các tài nguyên trong dịch vụ web.

Nghỉ ngơi và Python: Tiêu thụ API

Để viết mã tương tác với API REST, hầu hết các nhà phát triển Python đều chuyển sang

>>> import requests
>>> api_url = "https://jsonplaceholder.typicode.com/todos/10"
>>> response = requests.get(api_url)
>>> response.json()
{'userId': 1, 'id': 10, 'title': 'illo est ... aut', 'completed': True}

>>> todo = {"userId": 1, "title": "Wash car", "completed": True}
>>> response = requests.put(api_url, json=todo)
>>> response.json()
{'userId': 1, 'title': 'Wash car', 'completed': True, 'id': 10}

>>> response.status_code
200
2 để gửi các yêu cầu HTTP. Thư viện này trừu tượng hóa sự phức tạp của việc thực hiện các yêu cầu HTTP. Nó là một trong số ít các dự án đáng đối xử như thể nó là một phần của thư viện tiêu chuẩn.

Bạn sẽ lưu ý rằng một số điểm cuối có

$ python -m pip install requests
08 ở cuối. Ký hiệu này có nghĩa là bạn cần nối một số
$ python -m pip install requests
09 vào URL để nói với API còn lại mà
$ python -m pip install requests
10 bạn muốn làm việc cùng.

>>> response.status_code
200

>>> response.headers["Content-Type"]
'application/json; charset=utf-8'

Các điểm cuối được liệt kê ở trên chỉ đại diện cho một tài nguyên trong hệ thống. API REST sẵn sàng sản xuất thường có hàng chục hoặc thậm chí hàng trăm điểm cuối khác nhau để quản lý các tài nguyên trong dịch vụ web.

Nghỉ ngơi và Python: Tiêu thụ API

Để viết mã tương tác với API REST, hầu hết các nhà phát triển Python đều chuyển sang

>>> import requests
>>> api_url = "https://jsonplaceholder.typicode.com/todos/10"
>>> response = requests.get(api_url)
>>> response.json()
{'userId': 1, 'id': 10, 'title': 'illo est ... aut', 'completed': True}

>>> todo = {"userId": 1, "title": "Wash car", "completed": True}
>>> response = requests.put(api_url, json=todo)
>>> response.json()
{'userId': 1, 'title': 'Wash car', 'completed': True, 'id': 10}

>>> response.status_code
200
2 để gửi các yêu cầu HTTP. Thư viện này trừu tượng hóa sự phức tạp của việc thực hiện các yêu cầu HTTP. Nó là một trong số ít các dự án đáng đối xử như thể nó là một phần của thư viện tiêu chuẩn.

{
    "userId": 1,
    "title": "Buy milk",
    "completed": false
}

Để bắt đầu sử dụng

>>> import requests
>>> api_url = "https://jsonplaceholder.typicode.com/todos/10"
>>> response = requests.get(api_url)
>>> response.json()
{'userId': 1, 'id': 10, 'title': 'illo est ... aut', 'completed': True}

>>> todo = {"userId": 1, "title": "Wash car", "completed": True}
>>> response = requests.put(api_url, json=todo)
>>> response.json()
{'userId': 1, 'title': 'Wash car', 'completed': True, 'id': 10}

>>> response.status_code
200
2, bạn cần cài đặt nó trước. Bạn có thể sử dụng
$ python -m pip install requests
13 để cài đặt nó:

Bạn sẽ lưu ý rằng một số điểm cuối có

$ python -m pip install requests
08 ở cuối. Ký hiệu này có nghĩa là bạn cần nối một số
$ python -m pip install requests
09 vào URL để nói với API còn lại mà
$ python -m pip install requests
10 bạn muốn làm việc cùng.

>>> import requests
>>> api_url = "https://jsonplaceholder.typicode.com/todos"
>>> todo = {"userId": 1, "title": "Buy milk", "completed": False}
>>> response = requests.post(api_url, json=todo)
>>> response.json()
{'userId': 1, 'title': 'Buy milk', 'completed': False, 'id': 201}

>>> response.status_code
201

Các điểm cuối được liệt kê ở trên chỉ đại diện cho một tài nguyên trong hệ thống. API REST sẵn sàng sản xuất thường có hàng chục hoặc thậm chí hàng trăm điểm cuối khác nhau để quản lý các tài nguyên trong dịch vụ web.

Nghỉ ngơi và Python: Tiêu thụ API

Để viết mã tương tác với API REST, hầu hết các nhà phát triển Python đều chuyển sang

>>> import requests
>>> api_url = "https://jsonplaceholder.typicode.com/todos/10"
>>> response = requests.get(api_url)
>>> response.json()
{'userId': 1, 'id': 10, 'title': 'illo est ... aut', 'completed': True}

>>> todo = {"userId": 1, "title": "Wash car", "completed": True}
>>> response = requests.put(api_url, json=todo)
>>> response.json()
{'userId': 1, 'title': 'Wash car', 'completed': True, 'id': 10}

>>> response.status_code
200
2 để gửi các yêu cầu HTTP. Thư viện này trừu tượng hóa sự phức tạp của việc thực hiện các yêu cầu HTTP. Nó là một trong số ít các dự án đáng đối xử như thể nó là một phần của thư viện tiêu chuẩn.

Bạn sẽ lưu ý rằng một số điểm cuối có

$ python -m pip install requests
08 ở cuối. Ký hiệu này có nghĩa là bạn cần nối một số
$ python -m pip install requests
09 vào URL để nói với API còn lại mà
$ python -m pip install requests
10 bạn muốn làm việc cùng.

>>> import requests
>>> import json
>>> api_url = "https://jsonplaceholder.typicode.com/todos"
>>> todo = {"userId": 1, "title": "Buy milk", "completed": False}
>>> headers =  {"Content-Type":"application/json"}
>>> response = requests.post(api_url, data=json.dumps(todo), headers=headers)
>>> response.json()
{'userId': 1, 'title': 'Buy milk', 'completed': False, 'id': 201}

>>> response.status_code
201

Các điểm cuối được liệt kê ở trên chỉ đại diện cho một tài nguyên trong hệ thống. API REST sẵn sàng sản xuất thường có hàng chục hoặc thậm chí hàng trăm điểm cuối khác nhau để quản lý các tài nguyên trong dịch vụ web.

Sau đó, bạn gọi

$ python -m pip install requests
35, nhưng thay vì chuyển
$ python -m pip install requests
23 cho đối số
$ python -m pip install requests
38, trước tiên bạn gọi
$ python -m pip install requests
52 để tuần tự hóa nó. Sau khi nó nối tiếp, bạn chuyển nó đến đối số từ khóa
$ python -m pip install requests
53. Đối số
$ python -m pip install requests
53 cho biết
>>> import requests
>>> api_url = "https://jsonplaceholder.typicode.com/todos/10"
>>> response = requests.get(api_url)
>>> response.json()
{'userId': 1, 'id': 10, 'title': 'illo est ... aut', 'completed': True}

>>> todo = {"userId": 1, "title": "Wash car", "completed": True}
>>> response = requests.put(api_url, json=todo)
>>> response.json()
{'userId': 1, 'title': 'Wash car', 'completed': True, 'id': 10}

>>> response.status_code
200
2 Dữ liệu nào sẽ bao gồm trong yêu cầu. Bạn cũng chuyển từ điển
$ python -m pip install requests
46 sang
$ python -m pip install requests
35 để đặt các tiêu đề HTTP theo cách thủ công.

Khi bạn gọi

$ python -m pip install requests
35 như thế này, nó có tác dụng tương tự như mã trước đó nhưng cung cấp cho bạn nhiều quyền kiểm soát hơn đối với yêu cầu.

Khi API trả lời, bạn gọi

$ python -m pip install requests
59 để xem JSON. JSON bao gồm một
$ python -m pip install requests
60 được tạo cho
$ python -m pip install requests
23 mới. Mã trạng thái
{'userId': 1, 'title': 'Wash car', 'completed': True, 'id': 10}
2 cho bạn biết rằng một tài nguyên mới đã được tạo.

ĐẶT

Ngoài

>>> import requests
>>> api_url = "https://jsonplaceholder.typicode.com/todos/10"
>>> response = requests.get(api_url)
>>> response.json()
{'userId': 1, 'id': 10, 'title': 'illo est ... aut', 'completed': True}

>>> todo = {"userId": 1, "title": "Wash car", "completed": True}
>>> response = requests.put(api_url, json=todo)
>>> response.json()
{'userId': 1, 'title': 'Wash car', 'completed': True, 'id': 10}

>>> response.status_code
200
3 và
>>> import requests
>>> api_url = "https://jsonplaceholder.typicode.com/todos/10"
>>> response = requests.get(api_url)
>>> response.json()
{'userId': 1, 'id': 10, 'title': 'illo est ... aut', 'completed': True}

>>> todo = {"userId": 1, "title": "Wash car", "completed": True}
>>> response = requests.put(api_url, json=todo)
>>> response.json()
{'userId': 1, 'title': 'Wash car', 'completed': True, 'id': 10}

>>> response.status_code
200
4,
>>> import requests
>>> api_url = "https://jsonplaceholder.typicode.com/todos/10"
>>> response = requests.get(api_url)
>>> response.json()
{'userId': 1, 'id': 10, 'title': 'illo est ... aut', 'completed': True}

>>> todo = {"userId": 1, "title": "Wash car", "completed": True}
>>> response = requests.put(api_url, json=todo)
>>> response.json()
{'userId': 1, 'title': 'Wash car', 'completed': True, 'id': 10}

>>> response.status_code
200
2 cung cấp hỗ trợ cho tất cả các phương pháp HTTP khác mà bạn sẽ sử dụng với API REST. Mã sau đây gửi yêu cầu
>>> import requests
>>> api_url = "https://jsonplaceholder.typicode.com/todos/10"
>>> response = requests.get(api_url)
>>> response.json()
{'userId': 1, 'id': 10, 'title': 'illo est ... aut', 'completed': True}

>>> todo = {"userId": 1, "title": "Wash car", "completed": True}
>>> response = requests.put(api_url, json=todo)
>>> response.json()
{'userId': 1, 'title': 'Wash car', 'completed': True, 'id': 10}

>>> response.status_code
200
8 để cập nhật
$ python -m pip install requests
23 hiện có với dữ liệu mới. Bất kỳ dữ liệu nào được gửi với yêu cầu
>>> import requests
>>> api_url = "https://jsonplaceholder.typicode.com/todos/10"
>>> response = requests.get(api_url)
>>> response.json()
{'userId': 1, 'id': 10, 'title': 'illo est ... aut', 'completed': True}

>>> todo = {"userId": 1, "title": "Wash car", "completed": True}
>>> response = requests.put(api_url, json=todo)
>>> response.json()
{'userId': 1, 'title': 'Wash car', 'completed': True, 'id': 10}

>>> response.status_code
200
8 sẽ thay thế hoàn toàn các giá trị hiện có của
$ python -m pip install requests
23.

Bạn sẽ sử dụng cùng một điểm cuối của JsonPlaceholder mà bạn đã sử dụng với

>>> import requests
>>> api_url = "https://jsonplaceholder.typicode.com/todos/10"
>>> response = requests.get(api_url)
>>> response.json()
{'userId': 1, 'id': 10, 'title': 'illo est ... aut', 'completed': True}

>>> todo = {"userId": 1, "title": "Wash car", "completed": True}
>>> response = requests.put(api_url, json=todo)
>>> response.json()
{'userId': 1, 'title': 'Wash car', 'completed': True, 'id': 10}

>>> response.status_code
200
3 và
>>> import requests
>>> api_url = "https://jsonplaceholder.typicode.com/todos/10"
>>> response = requests.get(api_url)
>>> response.json()
{'userId': 1, 'id': 10, 'title': 'illo est ... aut', 'completed': True}

>>> todo = {"userId": 1, "title": "Wash car", "completed": True}
>>> response = requests.put(api_url, json=todo)
>>> response.json()
{'userId': 1, 'title': 'Wash car', 'completed': True, 'id': 10}

>>> response.status_code
200
4, nhưng lần này bạn sẽ nối
$ python -m pip install requests
72 vào cuối URL. Điều này cho API còn lại mà
$ python -m pip install requests
23 bạn muốn cập nhật:

>>>

>>> import requests
>>> api_url = "https://jsonplaceholder.typicode.com/todos/10"
>>> response = requests.get(api_url)
>>> response.json()
{'userId': 1, 'id': 10, 'title': 'illo est ... aut', 'completed': True}

>>> todo = {"userId": 1, "title": "Wash car", "completed": True}
>>> response = requests.put(api_url, json=todo)
>>> response.json()
{'userId': 1, 'title': 'Wash car', 'completed': True, 'id': 10}

>>> response.status_code
200

Tại đây, trước tiên bạn gọi

$ python -m pip install requests
20 để xem nội dung của
$ python -m pip install requests
23 hiện có. Tiếp theo, bạn gọi
$ python -m pip install requests
76 với dữ liệu JSON mới để thay thế các giá trị việc cần làm hiện tại. Bạn có thể thấy các giá trị mới khi bạn gọi
$ python -m pip install requests
59. Các yêu cầu
>>> import requests
>>> api_url = "https://jsonplaceholder.typicode.com/todos/10"
>>> response = requests.get(api_url)
>>> response.json()
{'userId': 1, 'id': 10, 'title': 'illo est ... aut', 'completed': True}

>>> todo = {"userId": 1, "title": "Wash car", "completed": True}
>>> response = requests.put(api_url, json=todo)
>>> response.json()
{'userId': 1, 'title': 'Wash car', 'completed': True, 'id': 10}

>>> response.status_code
200
8 thành công sẽ luôn trả về
{'userId': 1, 'title': 'Wash car', 'completed': True, 'id': 10}
1 thay vì
{'userId': 1, 'title': 'Wash car', 'completed': True, 'id': 10}
2 vì bạn không tạo ra một tài nguyên mới mà chỉ cập nhật một tài nguyên hiện có.

Tiếp theo, bạn sẽ sử dụng

$ python -m pip install requests
81 để sửa đổi giá trị của một trường cụ thể trên
$ python -m pip install requests
23 hiện có.
>>> import requests
>>> api_url = "https://jsonplaceholder.typicode.com/todos/10"
>>> response = requests.get(api_url)
>>> response.json()
{'userId': 1, 'id': 10, 'title': 'illo est ... aut', 'completed': True}

>>> todo = {"userId": 1, "title": "Wash car", "completed": True}
>>> response = requests.put(api_url, json=todo)
>>> response.json()
{'userId': 1, 'title': 'Wash car', 'completed': True, 'id': 10}

>>> response.status_code
200
9 khác với
>>> import requests
>>> api_url = "https://jsonplaceholder.typicode.com/todos/10"
>>> response = requests.get(api_url)
>>> response.json()
{'userId': 1, 'id': 10, 'title': 'illo est ... aut', 'completed': True}

>>> todo = {"userId": 1, "title": "Wash car", "completed": True}
>>> response = requests.put(api_url, json=todo)
>>> response.json()
{'userId': 1, 'title': 'Wash car', 'completed': True, 'id': 10}

>>> response.status_code
200
8 ở chỗ nó không thay thế hoàn toàn tài nguyên hiện có. Nó chỉ sửa đổi các giá trị được đặt trong JSON được gửi với yêu cầu.

Bạn sẽ sử dụng cùng một

$ python -m pip install requests
23 từ ví dụ cuối cùng để thử
$ python -m pip install requests
81. Đây là các giá trị hiện tại:

{'userId': 1, 'title': 'Wash car', 'completed': True, 'id': 10}

Bây giờ bạn có thể cập nhật

$ python -m pip install requests
87 với giá trị mới:

>>>

>>> import requests
>>> api_url = "https://jsonplaceholder.typicode.com/todos/10"
>>> todo = {"title": "Mow lawn"}
>>> response = requests.patch(api_url, json=todo)
>>> response.json()
{'userId': 1, 'id': 10, 'title': 'Mow lawn', 'completed': True}

>>> response.status_code
200

Tại đây, trước tiên bạn gọi

$ python -m pip install requests
20 để xem nội dung của
$ python -m pip install requests
23 hiện có. Tiếp theo, bạn gọi
$ python -m pip install requests
76 với dữ liệu JSON mới để thay thế các giá trị việc cần làm hiện tại. Bạn có thể thấy các giá trị mới khi bạn gọi
$ python -m pip install requests
59. Các yêu cầu
>>> import requests
>>> api_url = "https://jsonplaceholder.typicode.com/todos/10"
>>> response = requests.get(api_url)
>>> response.json()
{'userId': 1, 'id': 10, 'title': 'illo est ... aut', 'completed': True}

>>> todo = {"userId": 1, "title": "Wash car", "completed": True}
>>> response = requests.put(api_url, json=todo)
>>> response.json()
{'userId': 1, 'title': 'Wash car', 'completed': True, 'id': 10}

>>> response.status_code
200
8 thành công sẽ luôn trả về
{'userId': 1, 'title': 'Wash car', 'completed': True, 'id': 10}
1 thay vì
{'userId': 1, 'title': 'Wash car', 'completed': True, 'id': 10}
2 vì bạn không tạo ra một tài nguyên mới mà chỉ cập nhật một tài nguyên hiện có.

Tiếp theo, bạn sẽ sử dụng

$ python -m pip install requests
81 để sửa đổi giá trị của một trường cụ thể trên
$ python -m pip install requests
23 hiện có.
>>> import requests
>>> api_url = "https://jsonplaceholder.typicode.com/todos/10"
>>> response = requests.get(api_url)
>>> response.json()
{'userId': 1, 'id': 10, 'title': 'illo est ... aut', 'completed': True}

>>> todo = {"userId": 1, "title": "Wash car", "completed": True}
>>> response = requests.put(api_url, json=todo)
>>> response.json()
{'userId': 1, 'title': 'Wash car', 'completed': True, 'id': 10}

>>> response.status_code
200
9 khác với
>>> import requests
>>> api_url = "https://jsonplaceholder.typicode.com/todos/10"
>>> response = requests.get(api_url)
>>> response.json()
{'userId': 1, 'id': 10, 'title': 'illo est ... aut', 'completed': True}

>>> todo = {"userId": 1, "title": "Wash car", "completed": True}
>>> response = requests.put(api_url, json=todo)
>>> response.json()
{'userId': 1, 'title': 'Wash car', 'completed': True, 'id': 10}

>>> response.status_code
200
8 ở chỗ nó không thay thế hoàn toàn tài nguyên hiện có. Nó chỉ sửa đổi các giá trị được đặt trong JSON được gửi với yêu cầu.

>>>

$ python -m pip install requests
0

Tại đây, trước tiên bạn gọi

$ python -m pip install requests
20 để xem nội dung của
$ python -m pip install requests
23 hiện có. Tiếp theo, bạn gọi
$ python -m pip install requests
76 với dữ liệu JSON mới để thay thế các giá trị việc cần làm hiện tại. Bạn có thể thấy các giá trị mới khi bạn gọi
$ python -m pip install requests
59. Các yêu cầu
>>> import requests
>>> api_url = "https://jsonplaceholder.typicode.com/todos/10"
>>> response = requests.get(api_url)
>>> response.json()
{'userId': 1, 'id': 10, 'title': 'illo est ... aut', 'completed': True}

>>> todo = {"userId": 1, "title": "Wash car", "completed": True}
>>> response = requests.put(api_url, json=todo)
>>> response.json()
{'userId': 1, 'title': 'Wash car', 'completed': True, 'id': 10}

>>> response.status_code
200
8 thành công sẽ luôn trả về
{'userId': 1, 'title': 'Wash car', 'completed': True, 'id': 10}
1 thay vì
{'userId': 1, 'title': 'Wash car', 'completed': True, 'id': 10}
2 vì bạn không tạo ra một tài nguyên mới mà chỉ cập nhật một tài nguyên hiện có.

Tiếp theo, bạn sẽ sử dụng $ python -m pip install requests 81 để sửa đổi giá trị của một trường cụ thể trên $ python -m pip install requests 23 hiện có. >>> import requests >>> api_url = "https://jsonplaceholder.typicode.com/todos/10" >>> response = requests.get(api_url) >>> response.json() {'userId': 1, 'id': 10, 'title': 'illo est ... aut', 'completed': True} >>> todo = {"userId": 1, "title": "Wash car", "completed": True} >>> response = requests.put(api_url, json=todo) >>> response.json() {'userId': 1, 'title': 'Wash car', 'completed': True, 'id': 10} >>> response.status_code 200 9 khác với >>> import requests >>> api_url = "https://jsonplaceholder.typicode.com/todos/10" >>> response = requests.get(api_url) >>> response.json() {'userId': 1, 'id': 10, 'title': 'illo est ... aut', 'completed': True} >>> todo = {"userId": 1, "title": "Wash car", "completed": True} >>> response = requests.put(api_url, json=todo) >>> response.json() {'userId': 1, 'title': 'Wash car', 'completed': True, 'id': 10} >>> response.status_code 200 8 ở chỗ nó không thay thế hoàn toàn tài nguyên hiện có. Nó chỉ sửa đổi các giá trị được đặt trong JSON được gửi với yêu cầu.

Bạn sẽ sử dụng cùng một

$ python -m pip install requests
23 từ ví dụ cuối cùng để thử
$ python -m pip install requests
81. Đây là các giá trị hiện tại:

Bây giờ bạn có thể cập nhật $ python -m pip install requests 87 với giá trị mới:

Khi bạn gọi

$ python -m pip install requests
59, bạn có thể thấy rằng
$ python -m pip install requests
87 đã được cập nhật lên
$ python -m pip install requests
90.

XÓA BỎ

Cuối cùng nhưng không kém phần quan trọng, nếu bạn muốn loại bỏ hoàn toàn tài nguyên, thì bạn sử dụng >>> import requests >>> api_url = "https://jsonplaceholder.typicode.com/todos/10" >>> response = requests.get(api_url) >>> response.json() {'userId': 1, 'id': 10, 'title': 'illo est ... aut', 'completed': True} >>> todo = {"userId": 1, "title": "Wash car", "completed": True} >>> response = requests.put(api_url, json=todo) >>> response.json() {'userId': 1, 'title': 'Wash car', 'completed': True, 'id': 10} >>> response.status_code 200 5. Tại đây, mã để xóa $ python -m pip install requests 23:

Bạn gọi

$ python -m pip install requests
93 với URL API chứa ID cho
$ python -m pip install requests
23 bạn muốn xóa. Điều này gửi yêu cầu
>>> import requests
>>> api_url = "https://jsonplaceholder.typicode.com/todos/10"
>>> response = requests.get(api_url)
>>> response.json()
{'userId': 1, 'id': 10, 'title': 'illo est ... aut', 'completed': True}

>>> todo = {"userId": 1, "title": "Wash car", "completed": True}
>>> response = requests.put(api_url, json=todo)
>>> response.json()
{'userId': 1, 'title': 'Wash car', 'completed': True, 'id': 10}

>>> response.status_code
200
5 đến API REST, sau đó xóa tài nguyên phù hợp. Sau khi xóa tài nguyên, API sẽ gửi lại một đối tượng JSON trống cho biết tài nguyên đã bị xóa.

Thư viện
>>> import requests
>>> api_url = "https://jsonplaceholder.typicode.com/todos/10"
>>> response = requests.get(api_url)
>>> response.json()
{'userId': 1, 'id': 10, 'title': 'illo est ... aut', 'completed': True}

>>> todo = {"userId": 1, "title": "Wash car", "completed": True}
>>> response = requests.put(api_url, json=todo)
>>> response.json()
{'userId': 1, 'title': 'Wash car', 'completed': True, 'id': 10}

>>> response.status_code
200
2 là một công cụ tuyệt vời để làm việc với API REST và một phần không thể thiếu trong vành đai công cụ Python của bạn. Trong phần tiếp theo, bạn sẽ thay đổi bánh răng và xem xét những gì cần thiết để xây dựng API REST.
Nghỉ ngơi và Python: Xây dựng APIThiết kế API REST là một chủ đề lớn với nhiều lớp. Như với hầu hết mọi thứ trong công nghệ, có một loạt các ý kiến ​​về cách tiếp cận tốt nhất để xây dựng API. Trong phần này, bạn sẽ xem xét một số bước được đề xuất để theo dõi khi bạn xây dựng API.
Xác định tài nguyênBước đầu tiên bạn sẽ thực hiện khi bạn xây dựng API REST là xác định các tài nguyên mà API sẽ quản lý. Nó phổ biến để mô tả các tài nguyên này là các danh từ số nhiều, như
>>> import requests
>>> api_url = "https://jsonplaceholder.typicode.com/todos/10"
>>> todo = {"title": "Mow lawn"}
>>> response = requests.patch(api_url, json=todo)
>>> response.json()
{'userId': 1, 'id': 10, 'title': 'Mow lawn', 'completed': True}

>>> response.status_code
200
5,
$ python -m pip install requests
98 hoặc
$ python -m pip install requests
99. Khi bạn xác định các tài nguyên khác nhau trong dịch vụ web của mình, bạn sẽ xây dựng danh sách các danh từ mô tả các dữ liệu khác nhau mà người dùng có thể quản lý trong API.
Khi bạn làm điều này, hãy đảm bảo xem xét bất kỳ tài nguyên lồng nhau nào. Ví dụ:
>>> import requests
>>> api_url = "https://jsonplaceholder.typicode.com/todos/10"
>>> todo = {"title": "Mow lawn"}
>>> response = requests.patch(api_url, json=todo)
>>> response.json()
{'userId': 1, 'id': 10, 'title': 'Mow lawn', 'completed': True}

>>> response.status_code
200
5 có thể có
>>> import requests
>>> api_url = "https://jsonplaceholder.typicode.com/todos/1"
>>> response = requests.get(api_url)
>>> response.json()
{'userId': 1, 'id': 1, 'title': 'delectus aut autem', 'completed': False}
01 hoặc
$ python -m pip install requests
98 có thể chứa
>>> import requests
>>> api_url = "https://jsonplaceholder.typicode.com/todos/1"
>>> response = requests.get(api_url)
>>> response.json()
{'userId': 1, 'id': 1, 'title': 'delectus aut autem', 'completed': False}
03. Thiết lập các phân cấp tài nguyên này sẽ giúp ích khi bạn xác định các điểm cuối API.
Xác định tài nguyênBước đầu tiên bạn sẽ thực hiện khi bạn xây dựng API REST là xác định các tài nguyên mà API sẽ quản lý. Nó phổ biến để mô tả các tài nguyên này là các danh từ số nhiều, như
>>> import requests
>>> api_url = "https://jsonplaceholder.typicode.com/todos/10"
>>> todo = {"title": "Mow lawn"}
>>> response = requests.patch(api_url, json=todo)
>>> response.json()
{'userId': 1, 'id': 10, 'title': 'Mow lawn', 'completed': True}

>>> response.status_code
200
5,
$ python -m pip install requests
98 hoặc
$ python -m pip install requests
99. Khi bạn xác định các tài nguyên khác nhau trong dịch vụ web của mình, bạn sẽ xây dựng danh sách các danh từ mô tả các dữ liệu khác nhau mà người dùng có thể quản lý trong API.
Khi bạn làm điều này, hãy đảm bảo xem xét bất kỳ tài nguyên lồng nhau nào. Ví dụ:
>>> import requests
>>> api_url = "https://jsonplaceholder.typicode.com/todos/10"
>>> todo = {"title": "Mow lawn"}
>>> response = requests.patch(api_url, json=todo)
>>> response.json()
{'userId': 1, 'id': 10, 'title': 'Mow lawn', 'completed': True}

>>> response.status_code
200
5 có thể có
>>> import requests
>>> api_url = "https://jsonplaceholder.typicode.com/todos/1"
>>> response = requests.get(api_url)
>>> response.json()
{'userId': 1, 'id': 1, 'title': 'delectus aut autem', 'completed': False}
01 hoặc
$ python -m pip install requests
98 có thể chứa
>>> import requests
>>> api_url = "https://jsonplaceholder.typicode.com/todos/1"
>>> response = requests.get(api_url)
>>> response.json()
{'userId': 1, 'id': 1, 'title': 'delectus aut autem', 'completed': False}
03. Thiết lập các phân cấp tài nguyên này sẽ giúp ích khi bạn xác định các điểm cuối API.
Xác định điểm cuối của bạnBước đầu tiên bạn sẽ thực hiện khi bạn xây dựng API REST là xác định các tài nguyên mà API sẽ quản lý. Nó phổ biến để mô tả các tài nguyên này là các danh từ số nhiều, như
>>> import requests
>>> api_url = "https://jsonplaceholder.typicode.com/todos/10"
>>> todo = {"title": "Mow lawn"}
>>> response = requests.patch(api_url, json=todo)
>>> response.json()
{'userId': 1, 'id': 10, 'title': 'Mow lawn', 'completed': True}

>>> response.status_code
200
5,
$ python -m pip install requests
98 hoặc
$ python -m pip install requests
99. Khi bạn xác định các tài nguyên khác nhau trong dịch vụ web của mình, bạn sẽ xây dựng danh sách các danh từ mô tả các dữ liệu khác nhau mà người dùng có thể quản lý trong API.
Khi bạn làm điều này, hãy đảm bảo xem xét bất kỳ tài nguyên lồng nhau nào. Ví dụ:
>>> import requests
>>> api_url = "https://jsonplaceholder.typicode.com/todos/10"
>>> todo = {"title": "Mow lawn"}
>>> response = requests.patch(api_url, json=todo)
>>> response.json()
{'userId': 1, 'id': 10, 'title': 'Mow lawn', 'completed': True}

>>> response.status_code
200
5 có thể có
>>> import requests
>>> api_url = "https://jsonplaceholder.typicode.com/todos/1"
>>> response = requests.get(api_url)
>>> response.json()
{'userId': 1, 'id': 1, 'title': 'delectus aut autem', 'completed': False}
01 hoặc
$ python -m pip install requests
98 có thể chứa
>>> import requests
>>> api_url = "https://jsonplaceholder.typicode.com/todos/1"
>>> response = requests.get(api_url)
>>> response.json()
{'userId': 1, 'id': 1, 'title': 'delectus aut autem', 'completed': False}
03. Thiết lập các phân cấp tài nguyên này sẽ giúp ích khi bạn xác định các điểm cuối API.
Xác định điểm cuối của bạnBước đầu tiên bạn sẽ thực hiện khi bạn xây dựng API REST là xác định các tài nguyên mà API sẽ quản lý. Nó phổ biến để mô tả các tài nguyên này là các danh từ số nhiều, như
>>> import requests
>>> api_url = "https://jsonplaceholder.typicode.com/todos/10"
>>> todo = {"title": "Mow lawn"}
>>> response = requests.patch(api_url, json=todo)
>>> response.json()
{'userId': 1, 'id': 10, 'title': 'Mow lawn', 'completed': True}

>>> response.status_code
200
5,
$ python -m pip install requests
98 hoặc
$ python -m pip install requests
99. Khi bạn xác định các tài nguyên khác nhau trong dịch vụ web của mình, bạn sẽ xây dựng danh sách các danh từ mô tả các dữ liệu khác nhau mà người dùng có thể quản lý trong API.
Khi bạn làm điều này, hãy đảm bảo xem xét bất kỳ tài nguyên lồng nhau nào. Ví dụ:
>>> import requests
>>> api_url = "https://jsonplaceholder.typicode.com/todos/10"
>>> todo = {"title": "Mow lawn"}
>>> response = requests.patch(api_url, json=todo)
>>> response.json()
{'userId': 1, 'id': 10, 'title': 'Mow lawn', 'completed': True}

>>> response.status_code
200
5 có thể có
>>> import requests
>>> api_url = "https://jsonplaceholder.typicode.com/todos/1"
>>> response = requests.get(api_url)
>>> response.json()
{'userId': 1, 'id': 1, 'title': 'delectus aut autem', 'completed': False}
01 hoặc
$ python -m pip install requests
98 có thể chứa
>>> import requests
>>> api_url = "https://jsonplaceholder.typicode.com/todos/1"
>>> response = requests.get(api_url)
>>> response.json()
{'userId': 1, 'id': 1, 'title': 'delectus aut autem', 'completed': False}
03. Thiết lập các phân cấp tài nguyên này sẽ giúp ích khi bạn xác định các điểm cuối API.
Xác định điểm cuối của bạnBước đầu tiên bạn sẽ thực hiện khi bạn xây dựng API REST là xác định các tài nguyên mà API sẽ quản lý. Nó phổ biến để mô tả các tài nguyên này là các danh từ số nhiều, như
>>> import requests
>>> api_url = "https://jsonplaceholder.typicode.com/todos/10"
>>> todo = {"title": "Mow lawn"}
>>> response = requests.patch(api_url, json=todo)
>>> response.json()
{'userId': 1, 'id': 10, 'title': 'Mow lawn', 'completed': True}

>>> response.status_code
200
5,
$ python -m pip install requests
98 hoặc
$ python -m pip install requests
99. Khi bạn xác định các tài nguyên khác nhau trong dịch vụ web của mình, bạn sẽ xây dựng danh sách các danh từ mô tả các dữ liệu khác nhau mà người dùng có thể quản lý trong API.
Khi bạn làm điều này, hãy đảm bảo xem xét bất kỳ tài nguyên lồng nhau nào. Ví dụ:
>>> import requests
>>> api_url = "https://jsonplaceholder.typicode.com/todos/10"
>>> todo = {"title": "Mow lawn"}
>>> response = requests.patch(api_url, json=todo)
>>> response.json()
{'userId': 1, 'id': 10, 'title': 'Mow lawn', 'completed': True}

>>> response.status_code
200
5 có thể có
>>> import requests
>>> api_url = "https://jsonplaceholder.typicode.com/todos/1"
>>> response = requests.get(api_url)
>>> response.json()
{'userId': 1, 'id': 1, 'title': 'delectus aut autem', 'completed': False}
01 hoặc
$ python -m pip install requests
98 có thể chứa
>>> import requests
>>> api_url = "https://jsonplaceholder.typicode.com/todos/1"
>>> response = requests.get(api_url)
>>> response.json()
{'userId': 1, 'id': 1, 'title': 'delectus aut autem', 'completed': False}
03. Thiết lập các phân cấp tài nguyên này sẽ giúp ích khi bạn xác định các điểm cuối API.
Xác định điểm cuối của bạnBước đầu tiên bạn sẽ thực hiện khi bạn xây dựng API REST là xác định các tài nguyên mà API sẽ quản lý. Nó phổ biến để mô tả các tài nguyên này là các danh từ số nhiều, như
>>> import requests
>>> api_url = "https://jsonplaceholder.typicode.com/todos/10"
>>> todo = {"title": "Mow lawn"}
>>> response = requests.patch(api_url, json=todo)
>>> response.json()
{'userId': 1, 'id': 10, 'title': 'Mow lawn', 'completed': True}

>>> response.status_code
200
5,
$ python -m pip install requests
98 hoặc
$ python -m pip install requests
99. Khi bạn xác định các tài nguyên khác nhau trong dịch vụ web của mình, bạn sẽ xây dựng danh sách các danh từ mô tả các dữ liệu khác nhau mà người dùng có thể quản lý trong API.
Khi bạn làm điều này, hãy đảm bảo xem xét bất kỳ tài nguyên lồng nhau nào. Ví dụ:
>>> import requests
>>> api_url = "https://jsonplaceholder.typicode.com/todos/10"
>>> todo = {"title": "Mow lawn"}
>>> response = requests.patch(api_url, json=todo)
>>> response.json()
{'userId': 1, 'id': 10, 'title': 'Mow lawn', 'completed': True}

>>> response.status_code
200
5 có thể có
>>> import requests
>>> api_url = "https://jsonplaceholder.typicode.com/todos/1"
>>> response = requests.get(api_url)
>>> response.json()
{'userId': 1, 'id': 1, 'title': 'delectus aut autem', 'completed': False}
01 hoặc
$ python -m pip install requests
98 có thể chứa
>>> import requests
>>> api_url = "https://jsonplaceholder.typicode.com/todos/1"
>>> response = requests.get(api_url)
>>> response.json()
{'userId': 1, 'id': 1, 'title': 'delectus aut autem', 'completed': False}
03. Thiết lập các phân cấp tài nguyên này sẽ giúp ích khi bạn xác định các điểm cuối API.

Xác định điểm cuối của bạn

Bây giờ hãy xem một ví dụ về các điểm cuối cho một tài nguyên lồng nhau. Tại đây, bạn sẽ thấy các điểm cuối cho

>>> import requests
>>> api_url = "https://jsonplaceholder.typicode.com/todos/1"
>>> response = requests.get(api_url)
>>> response.json()
{'userId': 1, 'id': 1, 'title': 'delectus aut autem', 'completed': False}
03 được lồng theo tài nguyên
$ python -m pip install requests
98:

Phương pháp HTTPĐiểm cuối APISự mô tả
>>> import requests
>>> api_url = "https://jsonplaceholder.typicode.com/todos/10"
>>> response = requests.get(api_url)
>>> response.json()
{'userId': 1, 'id': 10, 'title': 'illo est ... aut', 'completed': True}

>>> todo = {"userId": 1, "title": "Wash car", "completed": True}
>>> response = requests.put(api_url, json=todo)
>>> response.json()
{'userId': 1, 'title': 'Wash car', 'completed': True, 'id': 10}

>>> response.status_code
200
3
>>> import requests
>>> api_url = "https://jsonplaceholder.typicode.com/todos/1"
>>> response = requests.get(api_url)
>>> response.json()
{'userId': 1, 'id': 1, 'title': 'delectus aut autem', 'completed': False}
21
Nhận một danh sách các khách.
>>> import requests
>>> api_url = "https://jsonplaceholder.typicode.com/todos/10"
>>> response = requests.get(api_url)
>>> response.json()
{'userId': 1, 'id': 10, 'title': 'illo est ... aut', 'completed': True}

>>> todo = {"userId": 1, "title": "Wash car", "completed": True}
>>> response = requests.put(api_url, json=todo)
>>> response.json()
{'userId': 1, 'title': 'Wash car', 'completed': True, 'id': 10}

>>> response.status_code
200
3
>>> import requests
>>> api_url = "https://jsonplaceholder.typicode.com/todos/1"
>>> response = requests.get(api_url)
>>> response.json()
{'userId': 1, 'id': 1, 'title': 'delectus aut autem', 'completed': False}
21
Nhận một danh sách các khách.
>>> import requests
>>> api_url = "https://jsonplaceholder.typicode.com/todos/1"
>>> response = requests.get(api_url)
>>> response.json()
{'userId': 1, 'id': 1, 'title': 'delectus aut autem', 'completed': False}
23
>>> import requests
>>> api_url = "https://jsonplaceholder.typicode.com/todos/1"
>>> response = requests.get(api_url)
>>> response.json()
{'userId': 1, 'id': 1, 'title': 'delectus aut autem', 'completed': False}
21
Nhận một danh sách các khách.
>>> import requests
>>> api_url = "https://jsonplaceholder.typicode.com/todos/1"
>>> response = requests.get(api_url)
>>> response.json()
{'userId': 1, 'id': 1, 'title': 'delectus aut autem', 'completed': False}
23
>>> import requests
>>> api_url = "https://jsonplaceholder.typicode.com/todos/1"
>>> response = requests.get(api_url)
>>> response.json()
{'userId': 1, 'id': 1, 'title': 'delectus aut autem', 'completed': False}
21
Nhận một danh sách các khách.
>>> import requests
>>> api_url = "https://jsonplaceholder.typicode.com/todos/1"
>>> response = requests.get(api_url)
>>> response.json()
{'userId': 1, 'id': 1, 'title': 'delectus aut autem', 'completed': False}
23
>>> import requests
>>> api_url = "https://jsonplaceholder.typicode.com/todos/1"
>>> response = requests.get(api_url)
>>> response.json()
{'userId': 1, 'id': 1, 'title': 'delectus aut autem', 'completed': False}
21
Nhận một danh sách các khách.
>>> import requests
>>> api_url = "https://jsonplaceholder.typicode.com/todos/1"
>>> response = requests.get(api_url)
>>> response.json()
{'userId': 1, 'id': 1, 'title': 'delectus aut autem', 'completed': False}
23
>>> import requests
>>> api_url = "https://jsonplaceholder.typicode.com/todos/1"
>>> response = requests.get(api_url)
>>> response.json()
{'userId': 1, 'id': 1, 'title': 'delectus aut autem', 'completed': False}
21
Nhận một danh sách các khách.

>>> import requests
>>> api_url = "https://jsonplaceholder.typicode.com/todos/1"
>>> response = requests.get(api_url)
>>> response.json()
{'userId': 1, 'id': 1, 'title': 'delectus aut autem', 'completed': False}
23

Nhận một khách.

>>> import requests
>>> api_url = "https://jsonplaceholder.typicode.com/todos/10"
>>> response = requests.get(api_url)
>>> response.json()
{'userId': 1, 'id': 10, 'title': 'illo est ... aut', 'completed': True}

>>> todo = {"userId": 1, "title": "Wash car", "completed": True}
>>> response = requests.put(api_url, json=todo)
>>> response.json()
{'userId': 1, 'title': 'Wash car', 'completed': True, 'id': 10}

>>> response.status_code
200
4

Tạo một khách mới.

>>> import requests >>> api_url = "https://jsonplaceholder.typicode.com/todos/10" >>> response = requests.get(api_url) >>> response.json() {'userId': 1, 'id': 10, 'title': 'illo est ... aut', 'completed': True} >>> todo = {"userId": 1, "title": "Wash car", "completed": True} >>> response = requests.put(api_url, json=todo) >>> response.json() {'userId': 1, 'title': 'Wash car', 'completed': True, 'id': 10} >>> response.status_code 200 8

Cập nhật một khách.

>>> import requests
>>> api_url = "https://jsonplaceholder.typicode.com/todos/10"
>>> response = requests.get(api_url)
>>> response.json()
{'userId': 1, 'id': 10, 'title': 'illo est ... aut', 'completed': True}

>>> todo = {"userId": 1, "title": "Wash car", "completed": True}
>>> response = requests.put(api_url, json=todo)
>>> response.json()
{'userId': 1, 'title': 'Wash car', 'completed': True, 'id': 10}

>>> response.status_code
200
9

$ python -m pip install requests
1

Cập nhật một phần một khách.elements to encode data. Each element has an opening and closing tag, with the data in between. Elements can be nested inside other elements. You can see this above, where several

>>> import requests
>>> api_url = "https://jsonplaceholder.typicode.com/todos/1"
>>> response = requests.get(api_url)
>>> response.json()
{'userId': 1, 'id': 1, 'title': 'delectus aut autem', 'completed': False}
38 tags are nested inside of
>>> import requests
>>> api_url = "https://jsonplaceholder.typicode.com/todos/1"
>>> response = requests.get(api_url)
>>> response.json()
{'userId': 1, 'id': 1, 'title': 'delectus aut autem', 'completed': False}
39.

>>> import requests
>>> api_url = "https://jsonplaceholder.typicode.com/todos/10"
>>> response = requests.get(api_url)
>>> response.json()
{'userId': 1, 'id': 10, 'title': 'illo est ... aut', 'completed': True}

>>> todo = {"userId": 1, "title": "Wash car", "completed": True}
>>> response = requests.put(api_url, json=todo)
>>> response.json()
{'userId': 1, 'title': 'Wash car', 'completed': True, 'id': 10}

>>> response.status_code
200
5

$ python -m pip install requests
2

Xóa một vị khách.

Với các điểm cuối này, bạn có thể quản lý

>>> import requests
>>> api_url = "https://jsonplaceholder.typicode.com/todos/1"
>>> response = requests.get(api_url)
>>> response.json()
{'userId': 1, 'id': 1, 'title': 'delectus aut autem', 'completed': False}
03 cho một sự kiện cụ thể trong hệ thống.

Đây là cách duy nhất để xác định điểm cuối cho các tài nguyên lồng nhau. Một số người thích sử dụng các chuỗi truy vấn để truy cập vào một tài nguyên lồng nhau. Một chuỗi truy vấn cho phép bạn gửi các tham số bổ sung với yêu cầu HTTP của bạn. Trong điểm cuối sau, bạn nối một chuỗi truy vấn để nhận >>> import requests >>> api_url = "https://jsonplaceholder.typicode.com/todos/1" >>> response = requests.get(api_url) >>> response.json() {'userId': 1, 'id': 1, 'title': 'delectus aut autem', 'completed': False} 03 cho một >>> import requests >>> api_url = "https://jsonplaceholder.typicode.com/todos/1" >>> response = requests.get(api_url) >>> response.json() {'userId': 1, 'id': 1, 'title': 'delectus aut autem', 'completed': False} 34 cụ thể:

Điểm cuối này sẽ lọc ra bất kỳ

>>> import requests
>>> api_url = "https://jsonplaceholder.typicode.com/todos/1"
>>> response = requests.get(api_url)
>>> response.json()
{'userId': 1, 'id': 1, 'title': 'delectus aut autem', 'completed': False}
03 nào không tham khảo
>>> import requests
>>> api_url = "https://jsonplaceholder.typicode.com/todos/1"
>>> response = requests.get(api_url)
>>> response.json()
{'userId': 1, 'id': 1, 'title': 'delectus aut autem', 'completed': False}
34 đã cho. Cũng như nhiều thứ trong thiết kế API, bạn cần quyết định phương thức nào phù hợp với dịch vụ web của bạn tốt nhất.

Bây giờ, bạn đã đề cập đến các điểm cuối, trong phần tiếp theo, bạn sẽ xem xét một số tùy chọn để định dạng dữ liệu trong API REST của bạn.

Chọn định dạng trao đổi dữ liệu của bạn

$ python -m pip install requests
3

Hai tùy chọn phổ biến để định dạng dữ liệu dịch vụ web là XML và JSON. Theo truyền thống, XML rất phổ biến với API SOAP, nhưng JSON phổ biến hơn với API REST. Để so sánh hai người, hãy xem một ví dụ

>>> import requests
>>> api_url = "https://jsonplaceholder.typicode.com/todos/1"
>>> response = requests.get(api_url)
>>> response.json()
{'userId': 1, 'id': 1, 'title': 'delectus aut autem', 'completed': False}
37 được định dạng là XML và JSON.

  1. Ở đây, cuốn sách được định dạng là XML: is the HTTP method type.
  2. XML sử dụng một loạt các phần tử để mã hóa dữ liệu. Mỗi phần tử có một thẻ mở và đóng, với dữ liệu ở giữa. Các yếu tố có thể được lồng bên trong các yếu tố khác. Bạn có thể thấy điều này ở trên, trong đó một số thẻ
    >>> import requests
    >>> api_url = "https://jsonplaceholder.typicode.com/todos/1"
    >>> response = requests.get(api_url)
    >>> response.json()
    {'userId': 1, 'id': 1, 'title': 'delectus aut autem', 'completed': False}
    
    38 được lồng bên trong
    >>> import requests
    >>> api_url = "https://jsonplaceholder.typicode.com/todos/1"
    >>> response = requests.get(api_url)
    >>> response.json()
    {'userId': 1, 'id': 1, 'title': 'delectus aut autem', 'completed': False}
    
    39.
    is the API endpoint.
  3. Bây giờ, hãy xem cùng một
    >>> import requests
    >>> api_url = "https://jsonplaceholder.typicode.com/todos/1"
    >>> response = requests.get(api_url)
    >>> response.json()
    {'userId': 1, 'id': 1, 'title': 'delectus aut autem', 'completed': False}
    
    37 trong JSON:
    is the HTTP version.
  4. JSON lưu trữ dữ liệu trong các cặp giá trị khóa tương tự như từ điển Python. Giống như XML, JSON hỗ trợ dữ liệu làm tổ ở bất kỳ cấp độ nào, vì vậy bạn có thể mô hình hóa dữ liệu phức tạp. is the API host.

Cả JSON và XML đều không tốt hơn so với người khác, nhưng có một ưu tiên cho JSON trong số các nhà phát triển API REST. Điều này đặc biệt đúng khi bạn ghép API REST với khung phía trước như React hoặc Vue.

$ python -m pip install requests
4

Thiết kế phản ứng thành công

Khi bạn đã chọn định dạng dữ liệu, bước tiếp theo là quyết định cách bạn sẽ trả lời các yêu cầu HTTP. Tất cả các phản hồi từ API REST của bạn sẽ có định dạng tương tự và bao gồm mã trạng thái HTTP thích hợp.

Trong phần này, bạn sẽ xem xét một số phản hồi HTTP ví dụ cho API giả thuyết quản lý hàng tồn kho của

>>> import requests
>>> api_url = "https://jsonplaceholder.typicode.com/todos/1"
>>> response = requests.get(api_url)
>>> response.json()
{'userId': 1, 'id': 1, 'title': 'delectus aut autem', 'completed': False}
41. Những ví dụ này sẽ cho bạn cảm giác về cách bạn nên định dạng các phản hồi API của bạn. Để làm cho mọi thứ rõ ràng, bạn sẽ xem xét các yêu cầu và phản hồi HTTP RAW thay vì sử dụng thư viện HTTP như
>>> import requests
>>> api_url = "https://jsonplaceholder.typicode.com/todos/10"
>>> response = requests.get(api_url)
>>> response.json()
{'userId': 1, 'id': 10, 'title': 'illo est ... aut', 'completed': True}

>>> todo = {"userId": 1, "title": "Wash car", "completed": True}
>>> response = requests.put(api_url, json=todo)
>>> response.json()
{'userId': 1, 'title': 'Wash car', 'completed': True, 'id': 10}

>>> response.status_code
200
2.

Để bắt đầu mọi thứ, hãy xem yêu cầu

>>> import requests
>>> api_url = "https://jsonplaceholder.typicode.com/todos/10"
>>> response = requests.get(api_url)
>>> response.json()
{'userId': 1, 'id': 10, 'title': 'illo est ... aut', 'completed': True}

>>> todo = {"userId": 1, "title": "Wash car", "completed": True}
>>> response = requests.put(api_url, json=todo)
>>> response.json()
{'userId': 1, 'title': 'Wash car', 'completed': True, 'id': 10}

>>> response.status_code
200
3 đến
>>> import requests
>>> api_url = "https://jsonplaceholder.typicode.com/todos/1"
>>> response = requests.get(api_url)
>>> response.json()
{'userId': 1, 'id': 1, 'title': 'delectus aut autem', 'completed': False}
44, trả về danh sách
>>> import requests
>>> api_url = "https://jsonplaceholder.typicode.com/todos/1"
>>> response = requests.get(api_url)
>>> response.json()
{'userId': 1, 'id': 1, 'title': 'delectus aut autem', 'completed': False}
41:

$ python -m pip install requests
5

Yêu cầu HTTP này được tạo thành từ bốn phần:

$ python -m pip install requests
6

>>> import requests
>>> api_url = "https://jsonplaceholder.typicode.com/todos/10"
>>> response = requests.get(api_url)
>>> response.json()
{'userId': 1, 'id': 10, 'title': 'illo est ... aut', 'completed': True}

>>> todo = {"userId": 1, "title": "Wash car", "completed": True}
>>> response = requests.put(api_url, json=todo)
>>> response.json()
{'userId': 1, 'title': 'Wash car', 'completed': True, 'id': 10}

>>> response.status_code
200
3 là loại phương pháp HTTP.

>>> import requests
>>> api_url = "https://jsonplaceholder.typicode.com/todos/1"
>>> response = requests.get(api_url)
>>> response.json()
{'userId': 1, 'id': 1, 'title': 'delectus aut autem', 'completed': False}
44 là điểm cuối API.

$ python -m pip install requests
7

>>> import requests
>>> api_url = "https://jsonplaceholder.typicode.com/todos/1"
>>> response = requests.get(api_url)
>>> response.json()
{'userId': 1, 'id': 1, 'title': 'delectus aut autem', 'completed': False}
48 là phiên bản HTTP.

>>> import requests
>>> api_url = "https://jsonplaceholder.typicode.com/todos/1"
>>> response = requests.get(api_url)
>>> response.json()
{'userId': 1, 'id': 1, 'title': 'delectus aut autem', 'completed': False}
49 là máy chủ API.

$ python -m pip install requests
8

Phản hồi này có mã trạng thái

>>> import requests
>>> api_url = "https://jsonplaceholder.typicode.com/todos/1"
>>> response = requests.get(api_url)
>>> response.json()
{'userId': 1, 'id': 1, 'title': 'delectus aut autem', 'completed': False}
69 để nói với người dùng rằng tài nguyên mới đã được tạo. Đảm bảo sử dụng
>>> import requests
>>> api_url = "https://jsonplaceholder.typicode.com/todos/1"
>>> response = requests.get(api_url)
>>> response.json()
{'userId': 1, 'id': 1, 'title': 'delectus aut autem', 'completed': False}
69 thay vì
>>> import requests
>>> api_url = "https://jsonplaceholder.typicode.com/todos/1"
>>> response = requests.get(api_url)
>>> response.json()
{'userId': 1, 'id': 1, 'title': 'delectus aut autem', 'completed': False}
53 cho tất cả các yêu cầu
>>> import requests
>>> api_url = "https://jsonplaceholder.typicode.com/todos/10"
>>> response = requests.get(api_url)
>>> response.json()
{'userId': 1, 'id': 10, 'title': 'illo est ... aut', 'completed': True}

>>> todo = {"userId": 1, "title": "Wash car", "completed": True}
>>> response = requests.put(api_url, json=todo)
>>> response.json()
{'userId': 1, 'title': 'Wash car', 'completed': True, 'id': 10}

>>> response.status_code
200
4 thành công.

Phản hồi này cũng bao gồm một bản sao của chiếc xe mới với

$ python -m pip install requests
60 được tạo bởi API. Điều quan trọng là phải gửi lại
$ python -m pip install requests
60 trong phản hồi để người dùng có thể sửa đổi tài nguyên một lần nữa.

Bây giờ hãy xem một yêu cầu

>>> import requests
>>> api_url = "https://jsonplaceholder.typicode.com/todos/10"
>>> response = requests.get(api_url)
>>> response.json()
{'userId': 1, 'id': 10, 'title': 'illo est ... aut', 'completed': True}

>>> todo = {"userId": 1, "title": "Wash car", "completed": True}
>>> response = requests.put(api_url, json=todo)
>>> response.json()
{'userId': 1, 'title': 'Wash car', 'completed': True, 'id': 10}

>>> response.status_code
200
8:

$ python -m pip install requests
9

Yêu cầu này sử dụng

$ python -m pip install requests
60 từ yêu cầu trước đó để cập nhật chiếc xe với tất cả dữ liệu mới. Một cách nhắc nhở,
>>> import requests
>>> api_url = "https://jsonplaceholder.typicode.com/todos/10"
>>> response = requests.get(api_url)
>>> response.json()
{'userId': 1, 'id': 10, 'title': 'illo est ... aut', 'completed': True}

>>> todo = {"userId": 1, "title": "Wash car", "completed": True}
>>> response = requests.put(api_url, json=todo)
>>> response.json()
{'userId': 1, 'title': 'Wash car', 'completed': True, 'id': 10}

>>> response.status_code
200
8 cập nhật tất cả các trường trên tài nguyên với dữ liệu mới. Ở đây, câu trả lời:

>>> import requests
>>> api_url = "https://jsonplaceholder.typicode.com/todos/1"
>>> response = requests.get(api_url)
>>> response.json()
{'userId': 1, 'id': 1, 'title': 'delectus aut autem', 'completed': False}
0

Phản hồi bao gồm một bản sao của

>>> import requests
>>> api_url = "https://jsonplaceholder.typicode.com/todos/1"
>>> response = requests.get(api_url)
>>> response.json()
{'userId': 1, 'id': 1, 'title': 'delectus aut autem', 'completed': False}
78 với dữ liệu mới. Một lần nữa, bạn luôn muốn gửi lại tài nguyên đầy đủ cho yêu cầu
>>> import requests
>>> api_url = "https://jsonplaceholder.typicode.com/todos/10"
>>> response = requests.get(api_url)
>>> response.json()
{'userId': 1, 'id': 10, 'title': 'illo est ... aut', 'completed': True}

>>> todo = {"userId": 1, "title": "Wash car", "completed": True}
>>> response = requests.put(api_url, json=todo)
>>> response.json()
{'userId': 1, 'title': 'Wash car', 'completed': True, 'id': 10}

>>> response.status_code
200
8. Điều tương tự cũng áp dụng cho yêu cầu
>>> import requests
>>> api_url = "https://jsonplaceholder.typicode.com/todos/10"
>>> response = requests.get(api_url)
>>> response.json()
{'userId': 1, 'id': 10, 'title': 'illo est ... aut', 'completed': True}

>>> todo = {"userId": 1, "title": "Wash car", "completed": True}
>>> response = requests.put(api_url, json=todo)
>>> response.json()
{'userId': 1, 'title': 'Wash car', 'completed': True, 'id': 10}

>>> response.status_code
200
9:

>>> import requests
>>> api_url = "https://jsonplaceholder.typicode.com/todos/1"
>>> response = requests.get(api_url)
>>> response.json()
{'userId': 1, 'id': 1, 'title': 'delectus aut autem', 'completed': False}
1

>>> import requests
>>> api_url = "https://jsonplaceholder.typicode.com/todos/10"
>>> response = requests.get(api_url)
>>> response.json()
{'userId': 1, 'id': 10, 'title': 'illo est ... aut', 'completed': True}

>>> todo = {"userId": 1, "title": "Wash car", "completed": True}
>>> response = requests.put(api_url, json=todo)
>>> response.json()
{'userId': 1, 'title': 'Wash car', 'completed': True, 'id': 10}

>>> response.status_code
200
9 yêu cầu chỉ cập nhật một phần của tài nguyên. Theo yêu cầu ở trên, các trường
>>> import requests
>>> api_url = "https://jsonplaceholder.typicode.com/todos/1"
>>> response = requests.get(api_url)
>>> response.json()
{'userId': 1, 'id': 1, 'title': 'delectus aut autem', 'completed': False}
82 và
>>> import requests
>>> api_url = "https://jsonplaceholder.typicode.com/todos/1"
>>> response = requests.get(api_url)
>>> response.json()
{'userId': 1, 'id': 1, 'title': 'delectus aut autem', 'completed': False}
83 sẽ được cập nhật với các giá trị mới. Ở đây, câu trả lời:

>>> import requests
>>> api_url = "https://jsonplaceholder.typicode.com/todos/1"
>>> response = requests.get(api_url)
>>> response.json()
{'userId': 1, 'id': 1, 'title': 'delectus aut autem', 'completed': False}
2

Phản hồi chứa một bản sao đầy đủ của

>>> import requests
>>> api_url = "https://jsonplaceholder.typicode.com/todos/1"
>>> response = requests.get(api_url)
>>> response.json()
{'userId': 1, 'id': 1, 'title': 'delectus aut autem', 'completed': False}
78. Như bạn có thể thấy, chỉ các trường
>>> import requests
>>> api_url = "https://jsonplaceholder.typicode.com/todos/1"
>>> response = requests.get(api_url)
>>> response.json()
{'userId': 1, 'id': 1, 'title': 'delectus aut autem', 'completed': False}
82 và
>>> import requests
>>> api_url = "https://jsonplaceholder.typicode.com/todos/1"
>>> response = requests.get(api_url)
>>> response.json()
{'userId': 1, 'id': 1, 'title': 'delectus aut autem', 'completed': False}
83 đã được cập nhật.

Cuối cùng, hãy xem API REST của bạn sẽ phản hồi như thế nào khi nhận được yêu cầu

>>> import requests
>>> api_url = "https://jsonplaceholder.typicode.com/todos/10"
>>> response = requests.get(api_url)
>>> response.json()
{'userId': 1, 'id': 10, 'title': 'illo est ... aut', 'completed': True}

>>> todo = {"userId": 1, "title": "Wash car", "completed": True}
>>> response = requests.put(api_url, json=todo)
>>> response.json()
{'userId': 1, 'title': 'Wash car', 'completed': True, 'id': 10}

>>> response.status_code
200
5. Tại đây, một yêu cầu
>>> import requests
>>> api_url = "https://jsonplaceholder.typicode.com/todos/10"
>>> response = requests.get(api_url)
>>> response.json()
{'userId': 1, 'id': 10, 'title': 'illo est ... aut', 'completed': True}

>>> todo = {"userId": 1, "title": "Wash car", "completed": True}
>>> response = requests.put(api_url, json=todo)
>>> response.json()
{'userId': 1, 'title': 'Wash car', 'completed': True, 'id': 10}

>>> response.status_code
200
5 để xóa
>>> import requests
>>> api_url = "https://jsonplaceholder.typicode.com/todos/1"
>>> response = requests.get(api_url)
>>> response.json()
{'userId': 1, 'id': 1, 'title': 'delectus aut autem', 'completed': False}
78:

Yêu cầu

>>> import requests
>>> api_url = "https://jsonplaceholder.typicode.com/todos/10"
>>> response = requests.get(api_url)
>>> response.json()
{'userId': 1, 'id': 10, 'title': 'illo est ... aut', 'completed': True}

>>> todo = {"userId": 1, "title": "Wash car", "completed": True}
>>> response = requests.put(api_url, json=todo)
>>> response.json()
{'userId': 1, 'title': 'Wash car', 'completed': True, 'id': 10}

>>> response.status_code
200
5 này cho API xóa
>>> import requests
>>> api_url = "https://jsonplaceholder.typicode.com/todos/1"
>>> response = requests.get(api_url)
>>> response.json()
{'userId': 1, 'id': 1, 'title': 'delectus aut autem', 'completed': False}
78 bằng ID
>>> import requests
>>> api_url = "https://jsonplaceholder.typicode.com/todos/1"
>>> response = requests.get(api_url)
>>> response.json()
{'userId': 1, 'id': 1, 'title': 'delectus aut autem', 'completed': False}
92. Ở đây, câu trả lời:

Phản hồi này chỉ bao gồm mã trạng thái

>>> import requests
>>> api_url = "https://jsonplaceholder.typicode.com/todos/1"
>>> response = requests.get(api_url)
>>> response.json()
{'userId': 1, 'id': 1, 'title': 'delectus aut autem', 'completed': False}
93. Mã trạng thái này cho người dùng biết rằng hoạt động đã thành công, nhưng không có nội dung nào được trả lại trong phản hồi. Điều này có ý nghĩa kể từ khi
>>> import requests
>>> api_url = "https://jsonplaceholder.typicode.com/todos/1"
>>> response = requests.get(api_url)
>>> response.json()
{'userId': 1, 'id': 1, 'title': 'delectus aut autem', 'completed': False}
78 đã bị xóa. Không có lý do gì để gửi một bản sao của nó trong phản hồi.

Các câu trả lời ở trên hoạt động tốt khi mọi thứ diễn ra theo kế hoạch, nhưng điều gì xảy ra nếu có vấn đề với yêu cầu? Trong phần tiếp theo, bạn sẽ xem xét cách API REST của bạn trả lời khi xảy ra lỗi.

Thiết kế phản hồi lỗi

Luôn luôn có một cơ hội yêu cầu API REST của bạn có thể thất bại. Đó là một ý tưởng tốt để xác định phản hồi lỗi sẽ như thế nào. Những phản hồi này nên bao gồm một mô tả về những gì lỗi xảy ra cùng với mã trạng thái thích hợp. Trong phần này, bạn sẽ xem xét một vài ví dụ.

Để bắt đầu, hãy xem yêu cầu tài nguyên không tồn tại trong API:

>>> import requests
>>> api_url = "https://jsonplaceholder.typicode.com/todos/1"
>>> response = requests.get(api_url)
>>> response.json()
{'userId': 1, 'id': 1, 'title': 'delectus aut autem', 'completed': False}
3

Tại đây, người dùng gửi yêu cầu

>>> import requests
>>> api_url = "https://jsonplaceholder.typicode.com/todos/10"
>>> response = requests.get(api_url)
>>> response.json()
{'userId': 1, 'id': 10, 'title': 'illo est ... aut', 'completed': True}

>>> todo = {"userId": 1, "title": "Wash car", "completed": True}
>>> response = requests.put(api_url, json=todo)
>>> response.json()
{'userId': 1, 'title': 'Wash car', 'completed': True, 'id': 10}

>>> response.status_code
200
3 đến
>>> import requests
>>> api_url = "https://jsonplaceholder.typicode.com/todos/1"
>>> response = requests.get(api_url)
>>> response.json()
{'userId': 1, 'id': 1, 'title': 'delectus aut autem', 'completed': False}
96, không tồn tại. API gửi lại phản hồi sau:

>>> import requests
>>> api_url = "https://jsonplaceholder.typicode.com/todos/1"
>>> response = requests.get(api_url)
>>> response.json()
{'userId': 1, 'id': 1, 'title': 'delectus aut autem', 'completed': False}
4

Phản hồi này bao gồm mã trạng thái

>>> import requests
>>> api_url = "https://jsonplaceholder.typicode.com/todos/1"
>>> response = requests.get(api_url)
>>> response.json()
{'userId': 1, 'id': 1, 'title': 'delectus aut autem', 'completed': False}
97. Cùng với điều này, phản hồi chứa một đối tượng JSON với thông báo lỗi mô tả. Cung cấp thông báo lỗi mô tả cung cấp cho người dùng nhiều bối cảnh hơn cho lỗi.

Bây giờ hãy xem phản hồi lỗi khi người dùng gửi yêu cầu không hợp lệ:

>>> import requests
>>> api_url = "https://jsonplaceholder.typicode.com/todos/1"
>>> response = requests.get(api_url)
>>> response.json()
{'userId': 1, 'id': 1, 'title': 'delectus aut autem', 'completed': False}
5

Yêu cầu

>>> import requests
>>> api_url = "https://jsonplaceholder.typicode.com/todos/10"
>>> response = requests.get(api_url)
>>> response.json()
{'userId': 1, 'id': 10, 'title': 'illo est ... aut', 'completed': True}

>>> todo = {"userId": 1, "title": "Wash car", "completed": True}
>>> response = requests.put(api_url, json=todo)
>>> response.json()
{'userId': 1, 'title': 'Wash car', 'completed': True, 'id': 10}

>>> response.status_code
200
4 này chứa JSON, nhưng nó không được định dạng chính xác. Nó thiếu một nẹp xoăn đóng (
>>> import requests
>>> api_url = "https://jsonplaceholder.typicode.com/todos/1"
>>> response = requests.get(api_url)
>>> response.json()
{'userId': 1, 'id': 1, 'title': 'delectus aut autem', 'completed': False}
99) ở cuối. API giành chiến thắng có thể xử lý dữ liệu này. Phản hồi lỗi cho người dùng biết về vấn đề:

>>> import requests
>>> api_url = "https://jsonplaceholder.typicode.com/todos/1"
>>> response = requests.get(api_url)
>>> response.json()
{'userId': 1, 'id': 1, 'title': 'delectus aut autem', 'completed': False}
6

Phản hồi này bao gồm thông báo lỗi mô tả cùng với mã trạng thái

>>> response.status_code
200

>>> response.headers["Content-Type"]
'application/json; charset=utf-8'
00, nói với người dùng rằng họ cần sửa chữa yêu cầu.

Có một số cách khác mà yêu cầu có thể sai ngay cả khi nó được định dạng đúng. Trong ví dụ tiếp theo này, người dùng gửi yêu cầu

>>> import requests
>>> api_url = "https://jsonplaceholder.typicode.com/todos/10"
>>> response = requests.get(api_url)
>>> response.json()
{'userId': 1, 'id': 10, 'title': 'illo est ... aut', 'completed': True}

>>> todo = {"userId": 1, "title": "Wash car", "completed": True}
>>> response = requests.put(api_url, json=todo)
>>> response.json()
{'userId': 1, 'title': 'Wash car', 'completed': True, 'id': 10}

>>> response.status_code
200
4 nhưng bao gồm một loại phương tiện không được hỗ trợ:

>>> import requests
>>> api_url = "https://jsonplaceholder.typicode.com/todos/1"
>>> response = requests.get(api_url)
>>> response.json()
{'userId': 1, 'id': 1, 'title': 'delectus aut autem', 'completed': False}
7

Trong yêu cầu này, người dùng gửi XML, nhưng API chỉ hỗ trợ JSON. API trả lời với điều này:

>>> import requests
>>> api_url = "https://jsonplaceholder.typicode.com/todos/1"
>>> response = requests.get(api_url)
>>> response.json()
{'userId': 1, 'id': 1, 'title': 'delectus aut autem', 'completed': False}
8

Phản hồi này bao gồm mã trạng thái

>>> response.status_code
200

>>> response.headers["Content-Type"]
'application/json; charset=utf-8'
02 để chỉ ra rằng yêu cầu
>>> import requests
>>> api_url = "https://jsonplaceholder.typicode.com/todos/10"
>>> response = requests.get(api_url)
>>> response.json()
{'userId': 1, 'id': 10, 'title': 'illo est ... aut', 'completed': True}

>>> todo = {"userId": 1, "title": "Wash car", "completed": True}
>>> response = requests.put(api_url, json=todo)
>>> response.json()
{'userId': 1, 'title': 'Wash car', 'completed': True, 'id': 10}

>>> response.status_code
200
4 bao gồm một định dạng dữ liệu được API hỗ trợ. Mã lỗi này có ý nghĩa đối với dữ liệu mà ở định dạng sai, nhưng những gì về dữ liệu mà không hợp lệ ngay cả với định dạng chính xác thì sao?

Trong ví dụ tiếp theo này, người dùng gửi yêu cầu

>>> import requests
>>> api_url = "https://jsonplaceholder.typicode.com/todos/10"
>>> response = requests.get(api_url)
>>> response.json()
{'userId': 1, 'id': 10, 'title': 'illo est ... aut', 'completed': True}

>>> todo = {"userId": 1, "title": "Wash car", "completed": True}
>>> response = requests.put(api_url, json=todo)
>>> response.json()
{'userId': 1, 'title': 'Wash car', 'completed': True, 'id': 10}

>>> response.status_code
200
4 nhưng bao gồm dữ liệu
>>> import requests
>>> api_url = "https://jsonplaceholder.typicode.com/todos/1"
>>> response = requests.get(api_url)
>>> response.json()
{'userId': 1, 'id': 1, 'title': 'delectus aut autem', 'completed': False}
78 không phù hợp với các trường của dữ liệu khác:

>>> import requests
>>> api_url = "https://jsonplaceholder.typicode.com/todos/1"
>>> response = requests.get(api_url)
>>> response.json()
{'userId': 1, 'id': 1, 'title': 'delectus aut autem', 'completed': False}
9

Trong yêu cầu này, người dùng thêm các trường

>>> response.status_code
200

>>> response.headers["Content-Type"]
'application/json; charset=utf-8'
06 và
>>> response.status_code
200

>>> response.headers["Content-Type"]
'application/json; charset=utf-8'
07 vào JSON. Các trường này không được hỗ trợ bởi API, vì vậy nó trả lời bằng một thông báo lỗi:

>>> response.status_code
200

>>> response.headers["Content-Type"]
'application/json; charset=utf-8'
0

Phản hồi này bao gồm mã trạng thái

>>> response.status_code
200

>>> response.headers["Content-Type"]
'application/json; charset=utf-8'
08. Mã trạng thái này chỉ ra rằng có bất kỳ vấn đề nào với yêu cầu, nhưng dữ liệu không hợp lệ. API REST cần xác thực dữ liệu đến. Nếu người dùng gửi dữ liệu với yêu cầu, thì API sẽ xác thực dữ liệu và thông báo cho người dùng về bất kỳ lỗi nào.

Trả lời các yêu cầu, cả thành công và sai lầm, là một trong những công việc quan trọng nhất của API REST. Nếu API của bạn trực quan và cung cấp các phản hồi chính xác, thì người dùng sẽ dễ dàng xây dựng các ứng dụng xung quanh dịch vụ web của bạn. May mắn thay, một số khung web Python tuyệt vời trừu tượng hóa sự phức tạp của việc xử lý các yêu cầu HTTP và trả lời trả lại. Bạn sẽ xem xét ba tùy chọn phổ biến trong phần tiếp theo.

Nghỉ ngơi và Python: Công cụ giao dịch

Trong phần này, bạn sẽ xem xét ba khung hình phổ biến để xây dựng các API REST trong Python. Mỗi khung có ưu và nhược điểm, vì vậy bạn sẽ phải đánh giá loại nào phù hợp nhất cho nhu cầu của bạn. Cuối cùng, trong các phần tiếp theo, bạn sẽ xem xét API REST trong mỗi khung. Tất cả các ví dụ sẽ dành cho một API tương tự quản lý một tập hợp các quốc gia.

Mỗi quốc gia sẽ có các lĩnh vực sau:

  • >>> response.status_code
    200
    
    >>> response.headers["Content-Type"]
    'application/json; charset=utf-8'
    
    09 là tên của đất nước.
    is the name of the country.
  • >>> response.status_code
    200
    
    >>> response.headers["Content-Type"]
    'application/json; charset=utf-8'
    
    10 là thủ đô của đất nước.
    is the capital of the country.
  • >>> response.status_code
    200
    
    >>> response.headers["Content-Type"]
    'application/json; charset=utf-8'
    
    11 là khu vực của đất nước tính bằng km vuông.
    is the area of the country in square kilometers.

Các lĩnh vực

>>> response.status_code
200

>>> response.headers["Content-Type"]
'application/json; charset=utf-8'
09,
>>> response.status_code
200

>>> response.headers["Content-Type"]
'application/json; charset=utf-8'
10 và
>>> response.status_code
200

>>> response.headers["Content-Type"]
'application/json; charset=utf-8'
11 lưu trữ dữ liệu về một quốc gia cụ thể ở đâu đó trên thế giới.

Hầu hết thời gian, dữ liệu được gửi từ API REST đến từ cơ sở dữ liệu. Kết nối với cơ sở dữ liệu nằm ngoài phạm vi của hướng dẫn này. Đối với các ví dụ dưới đây, bạn sẽ lưu trữ dữ liệu của mình trong danh sách Python. Ngoại lệ cho điều này là ví dụ về khung REST Django, chạy khỏi cơ sở dữ liệu SQLite mà Django tạo ra.

Để giữ cho mọi thứ nhất quán, bạn sẽ sử dụng

>>> response.status_code
200

>>> response.headers["Content-Type"]
'application/json; charset=utf-8'
15 làm điểm cuối chính của bạn cho cả ba khung. Bạn cũng sẽ sử dụng JSON làm định dạng dữ liệu của bạn cho cả ba khung.

Bây giờ bạn đã có nền cho API, bạn có thể chuyển sang phần tiếp theo, nơi bạn sẽ nhìn vào API còn lại trong bình.Flask.

Bình giữ nhiệt

Flask là một microframework Python được sử dụng để xây dựng các ứng dụng web và API REST. Flask cung cấp một xương sống vững chắc cho các ứng dụng của bạn trong khi để lại nhiều lựa chọn thiết kế tùy thuộc vào bạn. Công việc chính của Flask Flask là xử lý các yêu cầu HTTP và định tuyến chúng đến chức năng thích hợp trong ứng dụng.

Dưới đây là một ứng dụng bình ví dụ cho API REST:

>>> response.status_code
200

>>> response.headers["Content-Type"]
'application/json; charset=utf-8'
1

Ứng dụng này xác định điểm cuối API

>>> response.status_code
200

>>> response.headers["Content-Type"]
'application/json; charset=utf-8'
16 để quản lý danh sách các quốc gia. Nó xử lý hai loại yêu cầu khác nhau:

  1. >>> response.status_code
    200
    
    >>> response.headers["Content-Type"]
    'application/json; charset=utf-8'
    
    17 Trả về danh sách
    >>> response.status_code
    200
    
    >>> response.headers["Content-Type"]
    'application/json; charset=utf-8'
    
    15.
    returns the list of
    >>> response.status_code
    200
    
    >>> response.headers["Content-Type"]
    'application/json; charset=utf-8'
    
    15.
  2. >>> response.status_code
    200
    
    >>> response.headers["Content-Type"]
    'application/json; charset=utf-8'
    
    19 thêm
    >>> response.status_code
    200
    
    >>> response.headers["Content-Type"]
    'application/json; charset=utf-8'
    
    20 mới vào danh sách.
    adds a new
    >>> response.status_code
    200
    
    >>> response.headers["Content-Type"]
    'application/json; charset=utf-8'
    
    20 to the list.

Bạn có thể dùng thử ứng dụng này bằng cách cài đặt

>>> response.status_code
200

>>> response.headers["Content-Type"]
'application/json; charset=utf-8'
21 với
$ python -m pip install requests
13:

>>> response.status_code
200

>>> response.headers["Content-Type"]
'application/json; charset=utf-8'
2

Khi

>>> response.status_code
200

>>> response.headers["Content-Type"]
'application/json; charset=utf-8'
21 được cài đặt, hãy lưu mã trong một tệp có tên là
>>> response.status_code
200

>>> response.headers["Content-Type"]
'application/json; charset=utf-8'
24. Để chạy ứng dụng bình này, trước tiên bạn cần đặt một biến môi trường được gọi là
>>> response.status_code
200

>>> response.headers["Content-Type"]
'application/json; charset=utf-8'
25 thành
>>> response.status_code
200

>>> response.headers["Content-Type"]
'application/json; charset=utf-8'
24. Điều này cho Flask tập tin chứa ứng dụng của bạn.

Chạy lệnh sau bên trong thư mục chứa

>>> response.status_code
200

>>> response.headers["Content-Type"]
'application/json; charset=utf-8'
24:

>>> response.status_code
200

>>> response.headers["Content-Type"]
'application/json; charset=utf-8'
3

Điều này đặt

>>> response.status_code
200

>>> response.headers["Content-Type"]
'application/json; charset=utf-8'
25 thành
>>> response.status_code
200

>>> response.headers["Content-Type"]
'application/json; charset=utf-8'
24 trong vỏ hiện tại. Tùy chọn, bạn có thể đặt
>>> response.status_code
200

>>> response.headers["Content-Type"]
'application/json; charset=utf-8'
30 thành
>>> response.status_code
200

>>> response.headers["Content-Type"]
'application/json; charset=utf-8'
31, đặt bình ở chế độ gỡ lỗi:debug mode:

>>> response.status_code
200

>>> response.headers["Content-Type"]
'application/json; charset=utf-8'
4

Bên cạnh việc cung cấp thông báo lỗi hữu ích, chế độ gỡ lỗi sẽ kích hoạt tải lại ứng dụng sau khi tất cả các thay đổi mã. Không có chế độ gỡ lỗi, bạn phải khởi động lại máy chủ sau mỗi lần thay đổi.

Với tất cả các biến môi trường đã sẵn sàng, giờ đây bạn có thể khởi động máy chủ phát triển Flask bằng cách gọi

>>> response.status_code
200

>>> response.headers["Content-Type"]
'application/json; charset=utf-8'
32:

>>> response.status_code
200

>>> response.headers["Content-Type"]
'application/json; charset=utf-8'
5

Điều này bắt đầu một máy chủ chạy ứng dụng. Mở trình duyệt của bạn và truy cập

>>> response.status_code
200

>>> response.headers["Content-Type"]
'application/json; charset=utf-8'
33 và bạn sẽ thấy phản hồi sau:

>>> response.status_code
200

>>> response.headers["Content-Type"]
'application/json; charset=utf-8'
6

Phản hồi JSON này chứa ba

>>> response.status_code
200

>>> response.headers["Content-Type"]
'application/json; charset=utf-8'
15 được xác định vào đầu
>>> response.status_code
200

>>> response.headers["Content-Type"]
'application/json; charset=utf-8'
24. Hãy xem mã sau để xem cách thức hoạt động của nó:

>>> response.status_code
200

>>> response.headers["Content-Type"]
'application/json; charset=utf-8'
7

Mã này sử dụng

>>> response.status_code
200

>>> response.headers["Content-Type"]
'application/json; charset=utf-8'
36, một công cụ trang trí tuyến đường, để kết nối
>>> import requests
>>> api_url = "https://jsonplaceholder.typicode.com/todos/10"
>>> response = requests.get(api_url)
>>> response.json()
{'userId': 1, 'id': 10, 'title': 'illo est ... aut', 'completed': True}

>>> todo = {"userId": 1, "title": "Wash car", "completed": True}
>>> response = requests.put(api_url, json=todo)
>>> response.json()
{'userId': 1, 'title': 'Wash car', 'completed': True, 'id': 10}

>>> response.status_code
200
3 yêu cầu với một chức năng trong ứng dụng. Khi bạn truy cập
>>> response.status_code
200

>>> response.headers["Content-Type"]
'application/json; charset=utf-8'
16, Flask gọi chức năng được trang trí để xử lý yêu cầu HTTP và trả về phản hồi.

Trong mã trên,

>>> response.status_code
200

>>> response.headers["Content-Type"]
'application/json; charset=utf-8'
39 lấy
>>> response.status_code
200

>>> response.headers["Content-Type"]
'application/json; charset=utf-8'
15, đây là danh sách Python và chuyển đổi nó thành JSON với
>>> response.status_code
200

>>> response.headers["Content-Type"]
'application/json; charset=utf-8'
41. JSON này được trả lại trong phản hồi.

Bây giờ hãy xem

>>> response.status_code
200

>>> response.headers["Content-Type"]
'application/json; charset=utf-8'
42. Chức năng này xử lý các yêu cầu
>>> import requests
>>> api_url = "https://jsonplaceholder.typicode.com/todos/10"
>>> response = requests.get(api_url)
>>> response.json()
{'userId': 1, 'id': 10, 'title': 'illo est ... aut', 'completed': True}

>>> todo = {"userId": 1, "title": "Wash car", "completed": True}
>>> response = requests.put(api_url, json=todo)
>>> response.json()
{'userId': 1, 'title': 'Wash car', 'completed': True, 'id': 10}

>>> response.status_code
200
4 đến
>>> response.status_code
200

>>> response.headers["Content-Type"]
'application/json; charset=utf-8'
16 và cho phép bạn thêm một quốc gia mới vào danh sách. Nó sử dụng đối tượng bình
>>> response.status_code
200

>>> response.headers["Content-Type"]
'application/json; charset=utf-8'
45 để nhận thông tin về yêu cầu HTTP hiện tại:

>>> response.status_code
200

>>> response.headers["Content-Type"]
'application/json; charset=utf-8'
8

Hàm này thực hiện các hoạt động sau:

  1. Sử dụng
    >>> response.status_code
    200
    
    >>> response.headers["Content-Type"]
    'application/json; charset=utf-8'
    
    46 để kiểm tra xem yêu cầu có phải là JSON không
  2. Tạo một phiên bản
    >>> response.status_code
    200
    
    >>> response.headers["Content-Type"]
    'application/json; charset=utf-8'
    
    20 mới với
    >>> response.status_code
    200
    
    >>> response.headers["Content-Type"]
    'application/json; charset=utf-8'
    
    48
  3. Tìm
    $ python -m pip install requests
    
    60 tiếp theo và đặt nó trên
    >>> response.status_code
    200
    
    >>> response.headers["Content-Type"]
    'application/json; charset=utf-8'
    
    20
  4. Nối thêm
    >>> response.status_code
    200
    
    >>> response.headers["Content-Type"]
    'application/json; charset=utf-8'
    
    20 đến
    >>> response.status_code
    200
    
    >>> response.headers["Content-Type"]
    'application/json; charset=utf-8'
    
    15
  5. Trả lại
    >>> response.status_code
    200
    
    >>> response.headers["Content-Type"]
    'application/json; charset=utf-8'
    
    20 trong phản hồi cùng với mã trạng thái
    >>> import requests
    >>> api_url = "https://jsonplaceholder.typicode.com/todos/1"
    >>> response = requests.get(api_url)
    >>> response.json()
    {'userId': 1, 'id': 1, 'title': 'delectus aut autem', 'completed': False}
    
    69
  6. Trả về thông báo lỗi và mã trạng thái
    >>> response.status_code
    200
    
    >>> response.headers["Content-Type"]
    'application/json; charset=utf-8'
    
    02 nếu yêu cầu không phải là json

>>> response.status_code
200

>>> response.headers["Content-Type"]
'application/json; charset=utf-8'
42 cũng gọi
>>> response.status_code
200

>>> response.headers["Content-Type"]
'application/json; charset=utf-8'
57 để xác định
$ python -m pip install requests
60 cho
>>> response.status_code
200

>>> response.headers["Content-Type"]
'application/json; charset=utf-8'
20 mới:

>>> response.status_code
200

>>> response.headers["Content-Type"]
'application/json; charset=utf-8'
9

Hàm trợ giúp này sử dụng biểu thức máy phát để chọn tất cả ID quốc gia và sau đó gọi

>>> response.status_code
200

>>> response.headers["Content-Type"]
'application/json; charset=utf-8'
60 trên chúng để có được giá trị lớn nhất. Nó tăng giá trị này bởi
$ python -m pip install requests
24 để sử dụng ID tiếp theo.

Bạn có thể thử điểm cuối này trong shell bằng Curl công cụ dòng lệnh, cho phép bạn gửi các yêu cầu HTTP từ dòng lệnh. Tại đây, bạn sẽ thêm một

>>> response.status_code
200

>>> response.headers["Content-Type"]
'application/json; charset=utf-8'
20 mới vào danh sách
>>> response.status_code
200

>>> response.headers["Content-Type"]
'application/json; charset=utf-8'
15:

{
    "userId": 1,
    "title": "Buy milk",
    "completed": false
}
0

Lệnh Curl này có một số tùy chọn hữu ích để biết:

  • >>> response.status_code
    200
    
    >>> response.headers["Content-Type"]
    'application/json; charset=utf-8'
    
    64 Đặt phương thức HTTP cho yêu cầu.
    sets the HTTP method for the request.
  • >>> response.status_code
    200
    
    >>> response.headers["Content-Type"]
    'application/json; charset=utf-8'
    
    65 thêm một tiêu đề HTTP vào yêu cầu.
    adds an HTTP header to the request.
  • >>> response.status_code
    200
    
    >>> response.headers["Content-Type"]
    'application/json; charset=utf-8'
    
    66 Xác định dữ liệu yêu cầu.
    defines the request data.

Với các tùy chọn này được đặt, Curl sẽ gửi dữ liệu JSON theo yêu cầu

>>> import requests
>>> api_url = "https://jsonplaceholder.typicode.com/todos/10"
>>> response = requests.get(api_url)
>>> response.json()
{'userId': 1, 'id': 10, 'title': 'illo est ... aut', 'completed': True}

>>> todo = {"userId": 1, "title": "Wash car", "completed": True}
>>> response = requests.put(api_url, json=todo)
>>> response.json()
{'userId': 1, 'title': 'Wash car', 'completed': True, 'id': 10}

>>> response.status_code
200
4 với tiêu đề
$ python -m pip install requests
30 được đặt thành
$ python -m pip install requests
42. API REST trả về
>>> response.status_code
200

>>> response.headers["Content-Type"]
'application/json; charset=utf-8'
70 cùng với JSON cho
>>> response.status_code
200

>>> response.headers["Content-Type"]
'application/json; charset=utf-8'
20 mới mà bạn đã thêm.

Bạn có thể sử dụng Curl để gửi yêu cầu

>>> import requests
>>> api_url = "https://jsonplaceholder.typicode.com/todos/10"
>>> response = requests.get(api_url)
>>> response.json()
{'userId': 1, 'id': 10, 'title': 'illo est ... aut', 'completed': True}

>>> todo = {"userId": 1, "title": "Wash car", "completed": True}
>>> response = requests.put(api_url, json=todo)
>>> response.json()
{'userId': 1, 'title': 'Wash car', 'completed': True, 'id': 10}

>>> response.status_code
200
3 đến
>>> response.status_code
200

>>> response.headers["Content-Type"]
'application/json; charset=utf-8'
16 để xác nhận rằng
>>> response.status_code
200

>>> response.headers["Content-Type"]
'application/json; charset=utf-8'
20 mới đã được thêm vào. Nếu bạn không sử dụng
>>> response.status_code
200

>>> response.headers["Content-Type"]
'application/json; charset=utf-8'
64 trong lệnh Curl của mình, thì nó sẽ gửi yêu cầu
>>> import requests
>>> api_url = "https://jsonplaceholder.typicode.com/todos/10"
>>> response = requests.get(api_url)
>>> response.json()
{'userId': 1, 'id': 10, 'title': 'illo est ... aut', 'completed': True}

>>> todo = {"userId": 1, "title": "Wash car", "completed": True}
>>> response = requests.put(api_url, json=todo)
>>> response.json()
{'userId': 1, 'title': 'Wash car', 'completed': True, 'id': 10}

>>> response.status_code
200
3 theo mặc định:

{
    "userId": 1,
    "title": "Buy milk",
    "completed": false
}
1

Điều này trả về danh sách đầy đủ các quốc gia trong hệ thống, với quốc gia mới nhất ở phía dưới.

Đây chỉ là một mẫu của những gì bình có thể làm. Ứng dụng này có thể được mở rộng để bao gồm các điểm cuối cho tất cả các phương pháp HTTP khác. Flask cũng có một hệ sinh thái lớn của các phần mở rộng cung cấp chức năng bổ sung cho API REST, chẳng hạn như tích hợp cơ sở dữ liệu, xác thực và xử lý nền.

Khung nghỉ ngơi Django

Một lựa chọn phổ biến khác để xây dựng API REST là Django Rest Framework. Django REST Framework là một plugin Django bổ sung chức năng API REST trên đầu một dự án Django hiện có.

Để sử dụng Framework Django Rest, bạn cần một dự án Django để làm việc. Nếu bạn đã có một, thì bạn có thể áp dụng các mẫu trong phần cho dự án của mình. Nếu không, hãy theo dõi và bạn sẽ xây dựng một dự án Django và thêm vào khung Rest Django.

Đầu tiên, cài đặt

>>> response.status_code
200

>>> response.headers["Content-Type"]
'application/json; charset=utf-8'
77 và
>>> response.status_code
200

>>> response.headers["Content-Type"]
'application/json; charset=utf-8'
78 với
$ python -m pip install requests
13:

{
    "userId": 1,
    "title": "Buy milk",
    "completed": false
}
2

Điều này cài đặt

>>> response.status_code
200

>>> response.headers["Content-Type"]
'application/json; charset=utf-8'
77 và
>>> response.status_code
200

>>> response.headers["Content-Type"]
'application/json; charset=utf-8'
78. Bây giờ bạn có thể sử dụng công cụ
>>> response.status_code
200

>>> response.headers["Content-Type"]
'application/json; charset=utf-8'
82 để tạo dự án Django mới. Chạy lệnh sau để bắt đầu dự án của bạn:

{
    "userId": 1,
    "title": "Buy milk",
    "completed": false
}
3

Lệnh này tạo một thư mục mới trong thư mục hiện tại của bạn có tên là

>>> response.status_code
200

>>> response.headers["Content-Type"]
'application/json; charset=utf-8'
83. Bên trong thư mục này là tất cả các tệp bạn cần để chạy dự án Django của bạn. Tiếp theo, bạn sẽ tạo ra một ứng dụng Django mới trong dự án của bạn. Django chia nhỏ chức năng của một dự án thành các ứng dụng. Mỗi ứng dụng quản lý một phần riêng biệt của dự án.Django application inside your project. Django breaks up the functionality of a project into applications. Each application manages a distinct part of the project.

Để tạo ứng dụng, thay đổi các thư mục thành

>>> response.status_code
200

>>> response.headers["Content-Type"]
'application/json; charset=utf-8'
83 và chạy lệnh sau:

{
    "userId": 1,
    "title": "Buy milk",
    "completed": false
}
4

Điều này tạo ra một thư mục

>>> response.status_code
200

>>> response.headers["Content-Type"]
'application/json; charset=utf-8'
15 mới trong dự án của bạn. Bên trong thư mục này là các tệp cơ sở cho ứng dụng này.

Bây giờ bạn đã tạo ra một ứng dụng để làm việc, bạn cần nói với Django về nó. Bên cạnh thư mục

>>> response.status_code
200

>>> response.headers["Content-Type"]
'application/json; charset=utf-8'
15 mà bạn vừa tạo là một thư mục khác có tên là
>>> response.status_code
200

>>> response.headers["Content-Type"]
'application/json; charset=utf-8'
83. Thư mục này chứa các cấu hình và cài đặt cho dự án của bạn.

Mở tệp

>>> response.status_code
200

>>> response.headers["Content-Type"]
'application/json; charset=utf-8'
88 mà bên trong thư mục
>>> response.status_code
200

>>> response.headers["Content-Type"]
'application/json; charset=utf-8'
83. Thêm các dòng sau vào
>>> response.status_code
200

>>> response.headers["Content-Type"]
'application/json; charset=utf-8'
90 để kể Django về ứng dụng
>>> response.status_code
200

>>> response.headers["Content-Type"]
'application/json; charset=utf-8'
15 và khung REST Django:

{
    "userId": 1,
    "title": "Buy milk",
    "completed": false
}
5

Bạn đã thêm một dòng cho ứng dụng

>>> response.status_code
200

>>> response.headers["Content-Type"]
'application/json; charset=utf-8'
15 và
>>> response.status_code
200

>>> response.headers["Content-Type"]
'application/json; charset=utf-8'
93.

Bạn có thể tự hỏi tại sao bạn cần thêm

>>> response.status_code
200

>>> response.headers["Content-Type"]
'application/json; charset=utf-8'
93 vào danh sách ứng dụng. Bạn cần thêm nó vì Framework Django Rest chỉ là một ứng dụng Django khác. Các plugin Django là các ứng dụng Django được đóng gói và phân phối và bất cứ ai cũng có thể sử dụng.

Bước tiếp theo là tạo mô hình Django để xác định các trường dữ liệu của bạn. Bên trong ứng dụng

>>> response.status_code
200

>>> response.headers["Content-Type"]
'application/json; charset=utf-8'
15, Cập nhật
>>> response.status_code
200

>>> response.headers["Content-Type"]
'application/json; charset=utf-8'
96 với mã sau:

{
    "userId": 1,
    "title": "Buy milk",
    "completed": false
}
6

Mã này xác định mô hình

>>> response.status_code
200

>>> response.headers["Content-Type"]
'application/json; charset=utf-8'
97. Django sẽ sử dụng mô hình này để tạo bảng và cột cơ sở dữ liệu cho dữ liệu quốc gia.

Chạy các lệnh sau để cập nhật cơ sở dữ liệu Django dựa trên mô hình này:

{
    "userId": 1,
    "title": "Buy milk",
    "completed": false
}
7

Các lệnh này sử dụng di chuyển Django để tạo một bảng mới trong cơ sở dữ liệu.

Bảng này bắt đầu trống, nhưng thật tuyệt khi có một số dữ liệu ban đầu để bạn có thể kiểm tra khung Rest Django. Để làm điều này, bạn sẽ sử dụng một bộ đồ Django để tải một số dữ liệu trong cơ sở dữ liệu.

Sao chép và lưu dữ liệu JSON sau vào một tệp có tên

>>> response.status_code
200

>>> response.headers["Content-Type"]
'application/json; charset=utf-8'
98 và lưu nó bên trong thư mục
>>> response.status_code
200

>>> response.headers["Content-Type"]
'application/json; charset=utf-8'
15:

{
    "userId": 1,
    "title": "Buy milk",
    "completed": false
}
8

JSON này chứa các mục cơ sở dữ liệu cho ba quốc gia. Gọi lệnh sau để tải dữ liệu này trong cơ sở dữ liệu:

{
    "userId": 1,
    "title": "Buy milk",
    "completed": false
}
9

Điều này thêm ba hàng vào cơ sở dữ liệu.

Với điều đó, ứng dụng Django của bạn được thiết lập và điền với một số dữ liệu. Bây giờ bạn có thể bắt đầu thêm Framework Django Rest vào dự án.

Django Rest Framework lấy một mô hình Django hiện có và chuyển đổi nó thành JSON cho API REST. Nó làm điều này với các serializer mô hình. Một bộ tuần tự mô hình cho Django REST Framework cách chuyển đổi một thể hiện mô hình thành JSON và dữ liệu nào sẽ bao gồm.model serializers. A model serializer tells Django REST framework how to convert a model instance into JSON and what data to include.

Bạn có thể tạo bộ tuần tự của mình cho mô hình

>>> response.status_code
200

>>> response.headers["Content-Type"]
'application/json; charset=utf-8'
97 từ trên cao. Bắt đầu bằng cách tạo một tệp có tên
{
    "userId": 1,
    "title": "Buy milk",
    "completed": false
}
01 bên trong ứng dụng
>>> response.status_code
200

>>> response.headers["Content-Type"]
'application/json; charset=utf-8'
15. Sau khi bạn thực hiện điều đó, hãy thêm mã sau vào
{
    "userId": 1,
    "title": "Buy milk",
    "completed": false
}
01:

>>> import requests
>>> api_url = "https://jsonplaceholder.typicode.com/todos"
>>> todo = {"userId": 1, "title": "Buy milk", "completed": False}
>>> response = requests.post(api_url, json=todo)
>>> response.json()
{'userId': 1, 'title': 'Buy milk', 'completed': False, 'id': 201}

>>> response.status_code
201
0

Bộ tuần tự này,

{
    "userId": 1,
    "title": "Buy milk",
    "completed": false
}
04, các lớp con
{
    "userId": 1,
    "title": "Buy milk",
    "completed": false
}
05 để tự động tạo nội dung JSON dựa trên các trường mô hình của
>>> response.status_code
200

>>> response.headers["Content-Type"]
'application/json; charset=utf-8'
97. Trừ khi được chỉ định, một lớp con
{
    "userId": 1,
    "title": "Buy milk",
    "completed": false
}
07 sẽ bao gồm tất cả các trường từ mô hình Django trong JSON. Bạn có thể sửa đổi hành vi này bằng cách đặt
{
    "userId": 1,
    "title": "Buy milk",
    "completed": false
}
08 thành danh sách dữ liệu bạn muốn bao gồm.

Giống như Django, Django Rest Framework sử dụng các chế độ xem để truy vấn dữ liệu từ cơ sở dữ liệu để hiển thị cho người dùng. Thay vì viết các chế độ xem API REST từ đầu, bạn có thể phân lớp Django REST Framework, lớp ____409, có chế độ xem mặc định cho các hoạt động API REST phổ biến.

Dưới đây, một danh sách các hành động mà

{
    "userId": 1,
    "title": "Buy milk",
    "completed": false
}
09 cung cấp và các phương thức HTTP tương đương của chúng:

Phương pháp HTTPHoạt độngSự mô tả
>>> import requests
>>> api_url = "https://jsonplaceholder.typicode.com/todos/10"
>>> response = requests.get(api_url)
>>> response.json()
{'userId': 1, 'id': 10, 'title': 'illo est ... aut', 'completed': True}

>>> todo = {"userId": 1, "title": "Wash car", "completed": True}
>>> response = requests.put(api_url, json=todo)
>>> response.json()
{'userId': 1, 'title': 'Wash car', 'completed': True, 'id': 10}

>>> response.status_code
200
3
{
    "userId": 1,
    "title": "Buy milk",
    "completed": false
}
12
Nhận một danh sách các quốc gia.
>>> import requests
>>> api_url = "https://jsonplaceholder.typicode.com/todos/10"
>>> response = requests.get(api_url)
>>> response.json()
{'userId': 1, 'id': 10, 'title': 'illo est ... aut', 'completed': True}

>>> todo = {"userId": 1, "title": "Wash car", "completed": True}
>>> response = requests.put(api_url, json=todo)
>>> response.json()
{'userId': 1, 'title': 'Wash car', 'completed': True, 'id': 10}

>>> response.status_code
200
3
{
    "userId": 1,
    "title": "Buy milk",
    "completed": false
}
12
Nhận một danh sách các quốc gia.
{
    "userId": 1,
    "title": "Buy milk",
    "completed": false
}
14
Nhận một quốc gia duy nhất.
>>> import requests
>>> api_url = "https://jsonplaceholder.typicode.com/todos/10"
>>> response = requests.get(api_url)
>>> response.json()
{'userId': 1, 'id': 10, 'title': 'illo est ... aut', 'completed': True}

>>> todo = {"userId": 1, "title": "Wash car", "completed": True}
>>> response = requests.put(api_url, json=todo)
>>> response.json()
{'userId': 1, 'title': 'Wash car', 'completed': True, 'id': 10}

>>> response.status_code
200
4
{
    "userId": 1,
    "title": "Buy milk",
    "completed": false
}
16
Tạo một đất nước mới.
>>> import requests
>>> api_url = "https://jsonplaceholder.typicode.com/todos/10"
>>> response = requests.get(api_url)
>>> response.json()
{'userId': 1, 'id': 10, 'title': 'illo est ... aut', 'completed': True}

>>> todo = {"userId": 1, "title": "Wash car", "completed": True}
>>> response = requests.put(api_url, json=todo)
>>> response.json()
{'userId': 1, 'title': 'Wash car', 'completed': True, 'id': 10}

>>> response.status_code
200
8
{
    "userId": 1,
    "title": "Buy milk",
    "completed": false
}
18
Cập nhật một quốc gia.
>>> import requests
>>> api_url = "https://jsonplaceholder.typicode.com/todos/10"
>>> response = requests.get(api_url)
>>> response.json()
{'userId': 1, 'id': 10, 'title': 'illo est ... aut', 'completed': True}

>>> todo = {"userId": 1, "title": "Wash car", "completed": True}
>>> response = requests.put(api_url, json=todo)
>>> response.json()
{'userId': 1, 'title': 'Wash car', 'completed': True, 'id': 10}

>>> response.status_code
200
9
{
    "userId": 1,
    "title": "Buy milk",
    "completed": false
}
20
Cập nhật một phần một quốc gia.
>>> import requests
>>> api_url = "https://jsonplaceholder.typicode.com/todos/10"
>>> response = requests.get(api_url)
>>> response.json()
{'userId': 1, 'id': 10, 'title': 'illo est ... aut', 'completed': True}

>>> todo = {"userId": 1, "title": "Wash car", "completed": True}
>>> response = requests.put(api_url, json=todo)
>>> response.json()
{'userId': 1, 'title': 'Wash car', 'completed': True, 'id': 10}

>>> response.status_code
200
5

{
    "userId": 1,
    "title": "Buy milk",
    "completed": false
}
22

Xóa một quốc gia.

>>> import requests
>>> api_url = "https://jsonplaceholder.typicode.com/todos"
>>> todo = {"userId": 1, "title": "Buy milk", "completed": False}
>>> response = requests.post(api_url, json=todo)
>>> response.json()
{'userId': 1, 'title': 'Buy milk', 'completed': False, 'id': 201}

>>> response.status_code
201
1

Như bạn có thể thấy, những hành động này ánh xạ theo các phương thức HTTP tiêu chuẩn mà bạn mong đợi trong API REST. Bạn có thể ghi đè các hành động này trong lớp con của mình hoặc thêm các hành động bổ sung dựa trên các yêu cầu của API của bạn.

Dưới đây là mã cho lớp con

{
    "userId": 1,
    "title": "Buy milk",
    "completed": false
}
09 được gọi là
{
    "userId": 1,
    "title": "Buy milk",
    "completed": false
}
24. Lớp này sẽ tạo các chế độ xem cần thiết để quản lý dữ liệu
>>> response.status_code
200

>>> response.headers["Content-Type"]
'application/json; charset=utf-8'
97. Thêm mã sau vào
{
    "userId": 1,
    "title": "Buy milk",
    "completed": false
}
26 bên trong ứng dụng
>>> response.status_code
200

>>> response.headers["Content-Type"]
'application/json; charset=utf-8'
15:

Trong lớp này,

{
    "userId": 1,
    "title": "Buy milk",
    "completed": false
}
28 được đặt thành
{
    "userId": 1,
    "title": "Buy milk",
    "completed": false
}
04 và
{
    "userId": 1,
    "title": "Buy milk",
    "completed": false
}
30 được đặt thành
{
    "userId": 1,
    "title": "Buy milk",
    "completed": false
}
31. Điều này cho Django REST Framework sử dụng bộ nối tiếp và cách truy vấn cơ sở dữ liệu cho bộ chế độ xem cụ thể này.

>>> import requests
>>> api_url = "https://jsonplaceholder.typicode.com/todos"
>>> todo = {"userId": 1, "title": "Buy milk", "completed": False}
>>> response = requests.post(api_url, json=todo)
>>> response.json()
{'userId': 1, 'title': 'Buy milk', 'completed': False, 'id': 201}

>>> response.status_code
201
2

Khi các chế độ xem được tạo, chúng cần được ánh xạ tới các URL hoặc điểm cuối thích hợp. Để làm điều này, Django Rest Framework cung cấp một

{
    "userId": 1,
    "title": "Buy milk",
    "completed": false
}
32 sẽ tự động tạo URL cho
{
    "userId": 1,
    "title": "Buy milk",
    "completed": false
}
09.

Tạo tệp

{
    "userId": 1,
    "title": "Buy milk",
    "completed": false
}
34 trong ứng dụng
>>> response.status_code
200

>>> response.headers["Content-Type"]
'application/json; charset=utf-8'
15 và thêm mã sau vào tệp:

>>> import requests
>>> api_url = "https://jsonplaceholder.typicode.com/todos"
>>> todo = {"userId": 1, "title": "Buy milk", "completed": False}
>>> response = requests.post(api_url, json=todo)
>>> response.json()
{'userId': 1, 'title': 'Buy milk', 'completed': False, 'id': 201}

>>> response.status_code
201
3

Mã này tạo ra

{
    "userId": 1,
    "title": "Buy milk",
    "completed": false
}
32 và đăng ký
{
    "userId": 1,
    "title": "Buy milk",
    "completed": false
}
24 theo URL
>>> response.status_code
200

>>> response.headers["Content-Type"]
'application/json; charset=utf-8'
15. Điều này sẽ đặt tất cả các URL cho
{
    "userId": 1,
    "title": "Buy milk",
    "completed": false
}
24 theo
{
    "userId": 1,
    "title": "Buy milk",
    "completed": false
}
40.

>>> import requests
>>> api_url = "https://jsonplaceholder.typicode.com/todos"
>>> todo = {"userId": 1, "title": "Buy milk", "completed": False}
>>> response = requests.post(api_url, json=todo)
>>> response.json()
{'userId': 1, 'title': 'Buy milk', 'completed': False, 'id': 201}

>>> response.status_code
201
4

Cuối cùng, bạn cần cập nhật tệp cơ sở dự án

{
    "userId": 1,
    "title": "Buy milk",
    "completed": false
}
34 để bao gồm tất cả các URL
>>> response.status_code
200

>>> response.headers["Content-Type"]
'application/json; charset=utf-8'
15 trong dự án. Cập nhật tệp
{
    "userId": 1,
    "title": "Buy milk",
    "completed": false
}
34 bên trong thư mục
>>> response.status_code
200

>>> response.headers["Content-Type"]
'application/json; charset=utf-8'
83 với mã sau:

>>> import requests
>>> api_url = "https://jsonplaceholder.typicode.com/todos"
>>> todo = {"userId": 1, "title": "Buy milk", "completed": False}
>>> response = requests.post(api_url, json=todo)
>>> response.json()
{'userId': 1, 'title': 'Buy milk', 'completed': False, 'id': 201}

>>> response.status_code
201
5

Điều này đặt tất cả các URL theo

{
    "userId": 1,
    "title": "Buy milk",
    "completed": false
}
40. Bây giờ bạn đã sẵn sàng để thử API REST được hỗ trợ Django của bạn. Chạy lệnh sau trong thư mục root
>>> response.status_code
200

>>> response.headers["Content-Type"]
'application/json; charset=utf-8'
83 để khởi động máy chủ phát triển Django:

Máy chủ phát triển hiện đang chạy. Đi trước và gửi yêu cầu

>>> import requests
>>> api_url = "https://jsonplaceholder.typicode.com/todos/10"
>>> response = requests.get(api_url)
>>> response.json()
{'userId': 1, 'id': 10, 'title': 'illo est ... aut', 'completed': True}

>>> todo = {"userId": 1, "title": "Wash car", "completed": True}
>>> response = requests.put(api_url, json=todo)
>>> response.json()
{'userId': 1, 'title': 'Wash car', 'completed': True, 'id': 10}

>>> response.status_code
200
3 tới
{
    "userId": 1,
    "title": "Buy milk",
    "completed": false
}
40 để lấy danh sách tất cả các quốc gia trong dự án Django của bạn:

  • {
        "userId": 1,
        "title": "Buy milk",
        "completed": false
    }
    
    51
  • {
        "userId": 1,
        "title": "Buy milk",
        "completed": false
    }
    
    52
  • {
        "userId": 1,
        "title": "Buy milk",
        "completed": false
    }
    
    53
  • {
        "userId": 1,
        "title": "Buy milk",
        "completed": false
    }
    
    54
  • {
        "userId": 1,
        "title": "Buy milk",
        "completed": false
    }
    
    55
  • {
        "userId": 1,
        "title": "Buy milk",
        "completed": false
    }
    
    56

Django Rest Framework gửi lại phản hồi JSON với ba quốc gia bạn đã thêm trước đó. Phản hồi ở trên được định dạng cho khả năng đọc, vì vậy phản hồi của bạn sẽ trông khác nhau.

>>> import requests
>>> api_url = "https://jsonplaceholder.typicode.com/todos"
>>> todo = {"userId": 1, "title": "Buy milk", "completed": False}
>>> response = requests.post(api_url, json=todo)
>>> response.json()
{'userId': 1, 'title': 'Buy milk', 'completed': False, 'id': 201}

>>> response.status_code
201
6

{
    "userId": 1,
    "title": "Buy milk",
    "completed": false
}
32 bạn đã tạo trong
{
    "userId": 1,
    "title": "Buy milk",
    "completed": false
}
50 cung cấp URL cho các yêu cầu cho tất cả các điểm cuối API tiêu chuẩn:

Bạn có thể thử thêm một vài điểm cuối dưới đây. Gửi yêu cầu

>>> import requests
>>> api_url = "https://jsonplaceholder.typicode.com/todos/10"
>>> response = requests.get(api_url)
>>> response.json()
{'userId': 1, 'id': 10, 'title': 'illo est ... aut', 'completed': True}

>>> todo = {"userId": 1, "title": "Wash car", "completed": True}
>>> response = requests.put(api_url, json=todo)
>>> response.json()
{'userId': 1, 'title': 'Wash car', 'completed': True, 'id': 10}

>>> response.status_code
200
4 tới
{
    "userId": 1,
    "title": "Buy milk",
    "completed": false
}
40 để tạo một
>>> response.status_code
200

>>> response.headers["Content-Type"]
'application/json; charset=utf-8'
97 mới trong dự án Django của bạn:

>>> import requests
>>> api_url = "https://jsonplaceholder.typicode.com/todos"
>>> todo = {"userId": 1, "title": "Buy milk", "completed": False}
>>> response = requests.post(api_url, json=todo)
>>> response.json()
{'userId': 1, 'title': 'Buy milk', 'completed': False, 'id': 201}

>>> response.status_code
201
7

Điều này tạo ra một

>>> response.status_code
200

>>> response.headers["Content-Type"]
'application/json; charset=utf-8'
97 mới với JSON mà bạn đã gửi trong yêu cầu. Django REST Framework trả về mã trạng thái
>>> import requests
>>> api_url = "https://jsonplaceholder.typicode.com/todos/1"
>>> response = requests.get(api_url)
>>> response.json()
{'userId': 1, 'id': 1, 'title': 'delectus aut autem', 'completed': False}
69 và
>>> response.status_code
200

>>> response.headers["Content-Type"]
'application/json; charset=utf-8'
97 mới.

Bạn có thể xem

>>> response.status_code
200

>>> response.headers["Content-Type"]
'application/json; charset=utf-8'
97 hiện có bằng cách gửi yêu cầu đến
{
    "userId": 1,
    "title": "Buy milk",
    "completed": false
}
52 với
$ python -m pip install requests
60 hiện có. Chạy lệnh sau để nhận
>>> response.status_code
200

>>> response.headers["Content-Type"]
'application/json; charset=utf-8'
97 đầu tiên:

Phản hồi chứa thông tin cho >>> response.status_code 200 >>> response.headers["Content-Type"] 'application/json; charset=utf-8' 97 đầu tiên. Những ví dụ này chỉ đề cập đến các yêu cầu >>> import requests >>> api_url = "https://jsonplaceholder.typicode.com/todos/10" >>> response = requests.get(api_url) >>> response.json() {'userId': 1, 'id': 10, 'title': 'illo est ... aut', 'completed': True} >>> todo = {"userId": 1, "title": "Wash car", "completed": True} >>> response = requests.put(api_url, json=todo) >>> response.json() {'userId': 1, 'title': 'Wash car', 'completed': True, 'id': 10} >>> response.status_code 200 3 và >>> import requests >>> api_url = "https://jsonplaceholder.typicode.com/todos/10" >>> response = requests.get(api_url) >>> response.json() {'userId': 1, 'id': 10, 'title': 'illo est ... aut', 'completed': True} >>> todo = {"userId": 1, "title": "Wash car", "completed": True} >>> response = requests.put(api_url, json=todo) >>> response.json() {'userId': 1, 'title': 'Wash car', 'completed': True, 'id': 10} >>> response.status_code 200 4. Vui lòng dùng thử >>> import requests >>> api_url = "https://jsonplaceholder.typicode.com/todos/10" >>> response = requests.get(api_url) >>> response.json() {'userId': 1, 'id': 10, 'title': 'illo est ... aut', 'completed': True} >>> todo = {"userId": 1, "title": "Wash car", "completed": True} >>> response = requests.put(api_url, json=todo) >>> response.json() {'userId': 1, 'title': 'Wash car', 'completed': True, 'id': 10} >>> response.status_code 200 8, >>> import requests >>> api_url = "https://jsonplaceholder.typicode.com/todos/10" >>> response = requests.get(api_url) >>> response.json() {'userId': 1, 'id': 10, 'title': 'illo est ... aut', 'completed': True} >>> todo = {"userId": 1, "title": "Wash car", "completed": True} >>> response = requests.put(api_url, json=todo) >>> response.json() {'userId': 1, 'title': 'Wash car', 'completed': True, 'id': 10} >>> response.status_code 200 9 và >>> import requests >>> api_url = "https://jsonplaceholder.typicode.com/todos/10" >>> response = requests.get(api_url) >>> response.json() {'userId': 1, 'id': 10, 'title': 'illo est ... aut', 'completed': True} >>> todo = {"userId": 1, "title": "Wash car", "completed": True} >>> response = requests.put(api_url, json=todo) >>> response.json() {'userId': 1, 'title': 'Wash car', 'completed': True, 'id': 10} >>> response.status_code 200 5 yêu cầu của riêng bạn để xem cách bạn có thể quản lý hoàn toàn mô hình của mình từ API còn lại.

Như bạn đã thấy, Django Rest Framework là một lựa chọn tuyệt vời để xây dựng API REST, đặc biệt nếu bạn có dự án Django hiện có và bạn muốn thêm API.

Fastapi

>>> import requests
>>> api_url = "https://jsonplaceholder.typicode.com/todos"
>>> todo = {"userId": 1, "title": "Buy milk", "completed": False}
>>> response = requests.post(api_url, json=todo)
>>> response.json()
{'userId': 1, 'title': 'Buy milk', 'completed': False, 'id': 201}

>>> response.status_code
201
8

Fastapi là một khung web Python mà Tối ưu hóa cho việc xây dựng API. Nó sử dụng gợi ý loại Python và có hỗ trợ tích hợp cho các hoạt động Async. Fastapi được xây dựng trên đỉnh của Star Muff và Pydantic và rất hiệu suất.

Dưới đây là một ví dụ về API còn lại được xây dựng với Fastapi:

>>> import requests
>>> api_url = "https://jsonplaceholder.typicode.com/todos"
>>> todo = {"userId": 1, "title": "Buy milk", "completed": False}
>>> response = requests.post(api_url, json=todo)
>>> response.json()
{'userId': 1, 'title': 'Buy milk', 'completed': False, 'id': 201}

>>> response.status_code
201
9

Ứng dụng này sử dụng các tính năng của Fastapi để xây dựng API REST cho cùng một dữ liệu

>>> response.status_code
200

>>> response.headers["Content-Type"]
'application/json; charset=utf-8'
20 mà bạn đã thấy trong các ví dụ khác.

>>> import requests
>>> import json
>>> api_url = "https://jsonplaceholder.typicode.com/todos"
>>> todo = {"userId": 1, "title": "Buy milk", "completed": False}
>>> headers =  {"Content-Type":"application/json"}
>>> response = requests.post(api_url, data=json.dumps(todo), headers=headers)
>>> response.json()
{'userId': 1, 'title': 'Buy milk', 'completed': False, 'id': 201}

>>> response.status_code
201
0

Bạn có thể thử ứng dụng này bằng cách cài đặt

{
    "userId": 1,
    "title": "Buy milk",
    "completed": false
}
74 với
$ python -m pip install requests
13:

>>> import requests
>>> import json
>>> api_url = "https://jsonplaceholder.typicode.com/todos"
>>> todo = {"userId": 1, "title": "Buy milk", "completed": False}
>>> headers =  {"Content-Type":"application/json"}
>>> response = requests.post(api_url, data=json.dumps(todo), headers=headers)
>>> response.json()
{'userId': 1, 'title': 'Buy milk', 'completed': False, 'id': 201}

>>> response.status_code
201
1

Máy chủ hiện đang chạy. Mở một trình duyệt và truy cập

{
    "userId": 1,
    "title": "Buy milk",
    "completed": false
}
80. Bạn sẽ thấy Fastapi trả lời với điều này:

>>> import requests
>>> import json
>>> api_url = "https://jsonplaceholder.typicode.com/todos"
>>> todo = {"userId": 1, "title": "Buy milk", "completed": False}
>>> headers =  {"Content-Type":"application/json"}
>>> response = requests.post(api_url, data=json.dumps(todo), headers=headers)
>>> response.json()
{'userId': 1, 'title': 'Buy milk', 'completed': False, 'id': 201}

>>> response.status_code
201
2

Fastapi trả lời với một mảng JSON chứa danh sách

>>> response.status_code
200

>>> response.headers["Content-Type"]
'application/json; charset=utf-8'
15. Bạn cũng có thể thêm một quốc gia mới bằng cách gửi yêu cầu
>>> import requests
>>> api_url = "https://jsonplaceholder.typicode.com/todos/10"
>>> response = requests.get(api_url)
>>> response.json()
{'userId': 1, 'id': 10, 'title': 'illo est ... aut', 'completed': True}

>>> todo = {"userId": 1, "title": "Wash car", "completed": True}
>>> response = requests.put(api_url, json=todo)
>>> response.json()
{'userId': 1, 'title': 'Wash car', 'completed': True, 'id': 10}

>>> response.status_code
200
4 đến
>>> response.status_code
200

>>> response.headers["Content-Type"]
'application/json; charset=utf-8'
16:

>>> import requests
>>> import json
>>> api_url = "https://jsonplaceholder.typicode.com/todos"
>>> todo = {"userId": 1, "title": "Buy milk", "completed": False}
>>> headers =  {"Content-Type":"application/json"}
>>> response = requests.post(api_url, data=json.dumps(todo), headers=headers)
>>> response.json()
{'userId': 1, 'title': 'Buy milk', 'completed': False, 'id': 201}

>>> response.status_code
201
3

Bạn đã thêm một quốc gia mới. Bạn có thể xác nhận điều này với

>>> response.status_code
200

>>> response.headers["Content-Type"]
'application/json; charset=utf-8'
17:

>>> import requests
>>> import json
>>> api_url = "https://jsonplaceholder.typicode.com/todos"
>>> todo = {"userId": 1, "title": "Buy milk", "completed": False}
>>> headers =  {"Content-Type":"application/json"}
>>> response = requests.post(api_url, data=json.dumps(todo), headers=headers)
>>> response.json()
{'userId': 1, 'title': 'Buy milk', 'completed': False, 'id': 201}

>>> response.status_code
201
4

Fastapi trả lại một danh sách JSON bao gồm cả quốc gia mới mà bạn vừa thêm vào.

Bạn có thể nhận thấy rằng ứng dụng Fastapi trông tương tự như ứng dụng Flask. Giống như Flask, Fastapi có một bộ tính năng tập trung. Nó không cố gắng xử lý tất cả các khía cạnh của phát triển ứng dụng web. Nó được thiết kế để xây dựng API với các tính năng Python hiện đại.

Nếu bạn nhìn gần đỉnh

>>> response.status_code
200

>>> response.headers["Content-Type"]
'application/json; charset=utf-8'
24, thì bạn sẽ thấy một lớp gọi là
>>> response.status_code
200

>>> response.headers["Content-Type"]
'application/json; charset=utf-8'
97 kéo dài
{
    "userId": 1,
    "title": "Buy milk",
    "completed": false
}
87. Lớp
>>> response.status_code
200

>>> response.headers["Content-Type"]
'application/json; charset=utf-8'
97 mô tả cấu trúc của dữ liệu trong API còn lại:

>>> import requests
>>> import json
>>> api_url = "https://jsonplaceholder.typicode.com/todos"
>>> todo = {"userId": 1, "title": "Buy milk", "completed": False}
>>> headers =  {"Content-Type":"application/json"}
>>> response = requests.post(api_url, data=json.dumps(todo), headers=headers)
>>> response.json()
{'userId': 1, 'title': 'Buy milk', 'completed': False, 'id': 201}

>>> response.status_code
201
5

Đây là một ví dụ về mô hình Pydantic. Các mô hình Pydantic cung cấp một số tính năng hữu ích trong Fastapi. Họ sử dụng các chú thích loại Python để thực thi loại dữ liệu cho từng trường trong lớp. Điều này cho phép Fastapi tự động tạo JSON, với các loại dữ liệu chính xác, cho các điểm cuối API. Nó cũng cho phép Fastapi xác nhận JSON đến.

Nó rất hữu ích để làm nổi bật dòng đầu tiên vì có rất nhiều thứ đang diễn ra ở đó:

>>> import requests
>>> import json
>>> api_url = "https://jsonplaceholder.typicode.com/todos"
>>> todo = {"userId": 1, "title": "Buy milk", "completed": False}
>>> headers =  {"Content-Type":"application/json"}
>>> response = requests.post(api_url, data=json.dumps(todo), headers=headers)
>>> response.json()
{'userId': 1, 'title': 'Buy milk', 'completed': False, 'id': 201}

>>> response.status_code
201
6

Trong dòng này, bạn thấy

{
    "userId": 1,
    "title": "Buy milk",
    "completed": false
}
89, lưu trữ số nguyên cho ID của
>>> response.status_code
200

>>> response.headers["Content-Type"]
'application/json; charset=utf-8'
97. Nó sử dụng hàm
{
    "userId": 1,
    "title": "Buy milk",
    "completed": false
}
91 từ Pydantic để sửa đổi hành vi của
{
    "userId": 1,
    "title": "Buy milk",
    "completed": false
}
89. Trong ví dụ này, bạn đã vượt qua
{
    "userId": 1,
    "title": "Buy milk",
    "completed": false
}
91 Các đối số từ khóa
{
    "userId": 1,
    "title": "Buy milk",
    "completed": false
}
94 và
{
    "userId": 1,
    "title": "Buy milk",
    "completed": false
}
95.

Đối số đầu tiên,

{
    "userId": 1,
    "title": "Buy milk",
    "completed": false
}
94, được đặt thành
>>> response.status_code
200

>>> response.headers["Content-Type"]
'application/json; charset=utf-8'
57. Đối số này chỉ định một hàm để chạy bất cứ khi nào
>>> response.status_code
200

>>> response.headers["Content-Type"]
'application/json; charset=utf-8'
97 mới được tạo. Giá trị trả về sẽ được gán cho
{
    "userId": 1,
    "title": "Buy milk",
    "completed": false
}
89.

Đối số thứ hai,

{
    "userId": 1,
    "title": "Buy milk",
    "completed": false
}
95, được đặt thành
$ python -m pip install requests
60. Điều này cho Fastapi xuất ra khóa
>>> import requests
>>> api_url = "https://jsonplaceholder.typicode.com/todos"
>>> todo = {"userId": 1, "title": "Buy milk", "completed": False}
>>> response = requests.post(api_url, json=todo)
>>> response.json()
{'userId': 1, 'title': 'Buy milk', 'completed': False, 'id': 201}

>>> response.status_code
201
02 thay vì
>>> import requests
>>> api_url = "https://jsonplaceholder.typicode.com/todos"
>>> todo = {"userId": 1, "title": "Buy milk", "completed": False}
>>> response = requests.post(api_url, json=todo)
>>> response.json()
{'userId': 1, 'title': 'Buy milk', 'completed': False, 'id': 201}

>>> response.status_code
201
03 trong JSON:

>>> import requests
>>> import json
>>> api_url = "https://jsonplaceholder.typicode.com/todos"
>>> todo = {"userId": 1, "title": "Buy milk", "completed": False}
>>> headers =  {"Content-Type":"application/json"}
>>> response = requests.post(api_url, data=json.dumps(todo), headers=headers)
>>> response.json()
{'userId': 1, 'title': 'Buy milk', 'completed': False, 'id': 201}

>>> response.status_code
201
7

{
    "userId": 1,
    "title": "Buy milk",
    "completed": false
}
95 này cũng có nghĩa là bạn có thể sử dụng
$ python -m pip install requests
60 khi bạn tạo một
>>> response.status_code
200

>>> response.headers["Content-Type"]
'application/json; charset=utf-8'
97 mới. Bạn có thể thấy điều này trong danh sách
>>> response.status_code
200

>>> response.headers["Content-Type"]
'application/json; charset=utf-8'
15:

>>> import requests
>>> import json
>>> api_url = "https://jsonplaceholder.typicode.com/todos"
>>> todo = {"userId": 1, "title": "Buy milk", "completed": False}
>>> headers =  {"Content-Type":"application/json"}
>>> response = requests.post(api_url, data=json.dumps(todo), headers=headers)
>>> response.json()
{'userId': 1, 'title': 'Buy milk', 'completed': False, 'id': 201}

>>> response.status_code
201
8

Danh sách này chứa ba trường hợp

>>> response.status_code
200

>>> response.headers["Content-Type"]
'application/json; charset=utf-8'
97 cho các quốc gia ban đầu trong API. Các mô hình Pydantic cung cấp một số tính năng tuyệt vời và cho phép Fastapi dễ dàng xử lý dữ liệu JSON.

Bây giờ hãy xem hai chức năng API trong ứng dụng này. Đầu tiên,

>>> response.status_code
200

>>> response.headers["Content-Type"]
'application/json; charset=utf-8'
39, trả về danh sách
>>> response.status_code
200

>>> response.headers["Content-Type"]
'application/json; charset=utf-8'
15 cho các yêu cầu
>>> import requests
>>> api_url = "https://jsonplaceholder.typicode.com/todos/10"
>>> response = requests.get(api_url)
>>> response.json()
{'userId': 1, 'id': 10, 'title': 'illo est ... aut', 'completed': True}

>>> todo = {"userId": 1, "title": "Wash car", "completed": True}
>>> response = requests.put(api_url, json=todo)
>>> response.json()
{'userId': 1, 'title': 'Wash car', 'completed': True, 'id': 10}

>>> response.status_code
200
3 cho
>>> response.status_code
200

>>> response.headers["Content-Type"]
'application/json; charset=utf-8'
16:

>>> import requests
>>> import json
>>> api_url = "https://jsonplaceholder.typicode.com/todos"
>>> todo = {"userId": 1, "title": "Buy milk", "completed": False}
>>> headers =  {"Content-Type":"application/json"}
>>> response = requests.post(api_url, data=json.dumps(todo), headers=headers)
>>> response.json()
{'userId': 1, 'title': 'Buy milk', 'completed': False, 'id': 201}

>>> response.status_code
201
9

Fastapi sẽ tự động tạo JSON dựa trên các trường trong mô hình Pydantic và đặt đúng loại dữ liệu JSON từ các gợi ý loại Python.

Mô hình Pydantic cũng cung cấp một lợi ích khi bạn thực hiện yêu cầu

>>> import requests
>>> api_url = "https://jsonplaceholder.typicode.com/todos/10"
>>> response = requests.get(api_url)
>>> response.json()
{'userId': 1, 'id': 10, 'title': 'illo est ... aut', 'completed': True}

>>> todo = {"userId": 1, "title": "Wash car", "completed": True}
>>> response = requests.put(api_url, json=todo)
>>> response.json()
{'userId': 1, 'title': 'Wash car', 'completed': True, 'id': 10}

>>> response.status_code
200
4 cho
>>> response.status_code
200

>>> response.headers["Content-Type"]
'application/json; charset=utf-8'
16. Bạn có thể thấy trong hàm API thứ hai bên dưới rằng tham số
>>> response.status_code
200

>>> response.headers["Content-Type"]
'application/json; charset=utf-8'
20 có chú thích
>>> response.status_code
200

>>> response.headers["Content-Type"]
'application/json; charset=utf-8'
97:

>>> import requests
>>> api_url = "https://jsonplaceholder.typicode.com/todos/10"
>>> response = requests.get(api_url)
>>> response.json()
{'userId': 1, 'id': 10, 'title': 'illo est ... aut', 'completed': True}

>>> todo = {"userId": 1, "title": "Wash car", "completed": True}
>>> response = requests.put(api_url, json=todo)
>>> response.json()
{'userId': 1, 'title': 'Wash car', 'completed': True, 'id': 10}

>>> response.status_code
200
0

Chú thích loại này bảo Fastapi xác nhận JSON đến với

>>> response.status_code
200

>>> response.headers["Content-Type"]
'application/json; charset=utf-8'
97. Nếu nó không khớp, thì Fastapi sẽ trả về lỗi. Bạn có thể thử điều này bằng cách đưa ra yêu cầu với JSON không phù hợp với mô hình Pydantic:

>>> import requests
>>> api_url = "https://jsonplaceholder.typicode.com/todos/10"
>>> response = requests.get(api_url)
>>> response.json()
{'userId': 1, 'id': 10, 'title': 'illo est ... aut', 'completed': True}

>>> todo = {"userId": 1, "title": "Wash car", "completed": True}
>>> response = requests.put(api_url, json=todo)
>>> response.json()
{'userId': 1, 'title': 'Wash car', 'completed': True, 'id': 10}

>>> response.status_code
200
1

JSON trong yêu cầu này bị thiếu một giá trị cho

>>> response.status_code
200

>>> response.headers["Content-Type"]
'application/json; charset=utf-8'
11, vì vậy Fastapi đã trả lại phản hồi với mã trạng thái
>>> response.status_code
200

>>> response.headers["Content-Type"]
'application/json; charset=utf-8'
08 cũng như chi tiết về lỗi. Xác nhận này được thực hiện bởi mô hình Pydantic.

Ví dụ này chỉ làm trầy xước bề mặt của những gì Fastapi có thể làm. Với hiệu suất cao và các tính năng hiện đại như các chức năng

>>> import requests
>>> api_url = "https://jsonplaceholder.typicode.com/todos"
>>> todo = {"userId": 1, "title": "Buy milk", "completed": False}
>>> response = requests.post(api_url, json=todo)
>>> response.json()
{'userId': 1, 'title': 'Buy milk', 'completed': False, 'id': 201}

>>> response.status_code
201
20 và tài liệu tự động, Fastapi đáng để xem xét cho API REST tiếp theo của bạn.

Sự kết luận

API nghỉ ngơi ở khắp mọi nơi. Biết cách tận dụng Python để tiêu thụ và xây dựng API cho phép bạn làm việc với số lượng lớn dữ liệu mà dịch vụ web cung cấp.

Trong hướng dẫn này, bạn đã học được cách::

  • Xác định phong cách kiến ​​trúc còn lạiREST architecture style
  • Làm việc với các phương thức và mã trạng thái HTTPHTTP methods and status codes
  • Sử dụng
    >>> import requests
    >>> api_url = "https://jsonplaceholder.typicode.com/todos/10"
    >>> response = requests.get(api_url)
    >>> response.json()
    {'userId': 1, 'id': 10, 'title': 'illo est ... aut', 'completed': True}
    
    >>> todo = {"userId": 1, "title": "Wash car", "completed": True}
    >>> response = requests.put(api_url, json=todo)
    >>> response.json()
    {'userId': 1, 'title': 'Wash car', 'completed': True, 'id': 10}
    
    >>> response.status_code
    200
    
    2 để lấy và tiêu thụ dữ liệu từ API bên ngoài
    >>> import requests
    >>> api_url = "https://jsonplaceholder.typicode.com/todos/10"
    >>> response = requests.get(api_url)
    >>> response.json()
    {'userId': 1, 'id': 10, 'title': 'illo est ... aut', 'completed': True}
    
    >>> todo = {"userId": 1, "title": "Wash car", "completed": True}
    >>> response = requests.put(api_url, json=todo)
    >>> response.json()
    {'userId': 1, 'title': 'Wash car', 'completed': True, 'id': 10}
    
    >>> response.status_code
    200
    
    2
    to get and consume data from an external API
  • Xác định các điểm cuối, dữ liệu và phản hồi cho API RESTendpoints, data, and responses for a REST API
  • Bắt đầu với các công cụ Python để xây dựng API RESTREST API

Sử dụng các kỹ năng API Python REST mới của bạn, bạn sẽ không chỉ có thể tương tác với các dịch vụ web mà còn xây dựng API REST cho các ứng dụng của bạn. Các công cụ này mở ra cánh cửa cho một loạt các ứng dụng và dịch vụ thú vị, dựa trên dữ liệu.

API REST và ví dụ là gì?

API REST là một cách để hai hệ thống máy tính giao tiếp bằng cách sử dụng các công nghệ HTTP được tìm thấy trong trình duyệt và máy chủ web. Chia sẻ dữ liệu giữa hai hoặc nhiều hệ thống luôn là một yêu cầu cơ bản của phát triển phần mềm. Ví dụ, xem xét mua bảo hiểm xe máy.a way for two computer systems to communicate using the HTTP technologies found in web browsers and servers. Sharing data between two or more systems has always been a fundamental requirement of software development. For example, consider buying motor insurance.

Chúng ta có thể viết API REST trong Python không?

Flask Restful là một phần mở rộng cho Flask thêm hỗ trợ cho việc xây dựng API REST trong Python sử dụng Flask làm mặt sau. Nó khuyến khích các thực tiễn tốt nhất và rất dễ dàng để thiết lập. Flask Restful rất dễ dàng để nhặt nếu bạn đã quen thuộc với bình. Trong flask_restful, khối xây dựng chính là một tài nguyên.. It encourages best practices and is very easy to set up. Flask restful is very easy to pick up if you're already familiar with flask. In flask_restful , the main building block is a resource.

Khung API REST trong Python là gì?

REST (Chuyển giao trạng thái đại diện) Khung Python API là một tập hợp các tiện ích dựa trên Werkzeug để dễ dàng xây dựng API RESTful.Thật dễ dàng để cấu hình và mở rộng một cách dễ dàng.Nó không quyết định làm thế nào dữ liệu có thể được hiển thị, cũng như bất kỳ quyết định nào khác.Thay vào đó, đó là một kiến trúc dễ mở rộng để xây dựng API của một người.a set of utilities based on werkzeug to easily build Restful API. It is easy to configure and extends with ease. It does not decide how the data can be rendered, nor any other decision. Instead, it's an easily extensible architecture to build one's API.

Giải thích đơn giản API REST là gì?

API RESTful là kiểu kiến trúc cho giao diện chương trình ứng dụng (API) sử dụng các yêu cầu HTTP để truy cập và sử dụng dữ liệu.Dữ liệu đó có thể được sử dụng để có được, đặt, đăng và xóa các loại dữ liệu, trong đó đề cập đến việc đọc, cập nhật, tạo và xóa các hoạt động liên quan đến tài nguyên.an architectural style for an application program interface (API) that uses HTTP requests to access and use data. That data can be used to GET, PUT, POST and DELETE data types, which refers to the reading, updating, creating and deleting of operations concerning resources.