CODE VN

CODE VN

1643473323

Cách sử dụng ứng dụng Axios HTTP để yêu cầu dữ liệu JSON từ một API

Trong hướng dẫn này, bạn sẽ học cách sử dụng ứng dụng khách Axios HTTP để yêu cầu dữ liệu JSON từ một API. Sau đó, bạn sẽ học cách nhận phản hồi JSON, lặp qua dữ liệu mà phản hồi này chứa và đặt trạng thái của thành phần React của bạn dựa trên dữ liệu này

Bắt đầu nào!

Lưu ý: Hướng dẫn này giả định rằng bạn đang làm việc trong một ứng dụng React đã được tạo bằng cách sử dụng create-react-app.

Yêu cầu dữ liệu JSON

Phần đầu tiên của việc lặp qua một mảng JSON liên quan đến việc thực sự yêu cầu dữ liệu! Để yêu cầu dữ liệu từ một API, chúng tôi phải bắt đầu bằng cách sử dụng một ứng dụng khách HTTP. Trong hướng dẫn này, chúng tôi đã chọn Axios làm thư viện ứng dụng khách HTTP mà chúng tôi lựa chọn. Có rất nhiều lựa chọn thay thế! Tìm nạp là một ứng dụng khách gốc, tuyệt vời mà bạn có thể sử dụng nếu bạn đang cố gắng hạn chế số lượng phần phụ thuộc mà bạn đang sử dụng trong ứng dụng của mình.

Để tải xuống Axios, hãy điều hướng đến thư mục dự án gốc nơi chứa tệp của bạn và package.jsonchạy lệnh:. npm install --save axiosBây giờ bạn đã cài đặt Axios bên trong dự án React của mình và có thể bắt đầu sử dụng nó!

Trong đoạn mã dưới đây, bạn sẽ thấy lớp vỏ cơ bản của một SolarSystemthành phần. Công việc của thành phần này là yêu cầu danh sách các hành tinh từ máy chủ thông qua HTTP và sau đó hiển thị danh sách các Planetthành phần dựa trên phản hồi. Số lượng khí khổng lồ cũng sẽ cần được tính bằng cách lặp qua mảng JSON có trong phản hồi.

class SolarSystem Extends React.Component {
    constructor(props) {
        super(props);

        this.state = {
            planets: [],
            gasGiantsCount: 0
        }
    }

    componentDidMount() {
        ...
    }

    render() {
        ...
    }
}

Đầu tiên, bạn sẽ cần thiết lập planetstrạng thái của thành phần dựa trên danh sách các hành tinh được yêu cầu trong componentDidMountphương thức vòng đời. Phương componentDidMountthức vòng đời sẽ đảm bảo rằng dữ liệu của hành tinh chỉ được yêu cầu sau khi kết xuất ban đầu của SolarSystemthành phần. Điều này rất hữu ích vì bạn có thể hiển thị một màn hình tải đơn giản trong khi đợi yêu cầu hoàn tất.

Dưới đây là mã được cập nhật cho biết cách sử dụng Axios để thực hiện yêu cầu đối với API hành tinh riêng.

import axios from 'axios';

class SolarSystem Extends React.Component {
    constructor(props) {
        super(props);

        this.state = {
            planets: [],
            gasGiantsCount: 0
        }
    }

    async componentDidMount() {
        const { data: planets }  = await axios.get(this.props.planetApiUrl),
                  gasGiantsCount = planets.filter(planet => planet.isGasGiant).length;

        this.setState({ planets, gasGiantsCount });
    }

    render() {
        ...
    }
}

Wow, thật dễ dàng! Trong đoạn mã trên, trước tiên bạn đã nhập thư viện máy khách Axios HTTP. Sau đó, bạn đã đánh dấu componentDidMountlà một asyncchức năng. Điều này cho phép sử dụng awaittừ khóa để giải quyết Promisetrả về từ cuộc gọi đến axios.get.

Sau khi phản hồi được tải thành công, sau đó bạn có quyền truy cập vào đối tượng phản hồi Axios. Một trong những điều thú vị về Axios là nó tự động phân tích cú pháp JSON cho bạn! Bạn có thể truy cập JSON này trên datatrường của đối tượng phản hồi. Trong đoạn mã trên, chúng tôi sử dụng khả năng hủy cấu trúc đối tượng của JavaScript để lấy datatrường của đối tượng phản hồi và đổi tên nó thành planets. Trong trường hợp này, datatrường bao gồm mảng JSON đã được phân tích cú pháp của chúng ta.

Với quyền truy cập vào mảng JSON bạn cần, sau đó bạn lặp lại nó bằng cách sử dụng một trong các hàm nguyên mẫu Mảng của JavaScript. Trong trường hợp này, bạn có thể thấy rằng mã của bạn lặp lại trên các hành tinh và đếm số lượng khí khổng lồ trong hệ mặt trời.

Cuối cùng, bạn sử dụng setStatehàm để thiết lập trạng thái planetsgasGiantsCounttrạng thái của thành phần.

Với dữ liệu của bạn được yêu cầu, bây giờ đã đến lúc tải chế độ xem của bạn. Hãy nhớ rằng, thành phần này chỉ muốn hiển thị danh sách các Planetthành phần. Điều này có thể đạt được bằng cách thực hiện renderchức năng sau.

 ...

    render() {
        const { planets, gasGiantsCount } = this.state;

        const planetComponents = planets.map(planet => <Planet name={planet.name} type={planet.type} />);

        return (
            <div>
                <h2>{gasGiantsCount}</h2>
                <ul>{planetComponents}</ul>
            </div>
        )
    }
}

Làm việc với mảng JSON là một kỹ năng quan trọng khi tạo bất kỳ ứng dụng web nào. Trong React, bạn có thể làm việc với các mảng JSON dễ dàng bằng cách sử dụng một ứng dụng khách HTTP như Axios để giúp bạn với những thứ như phân tích cú pháp tự động của JSON. Các công cụ như Axios sẽ giúp công việc của bạn trở nên dễ dàng hơn bằng cách cho phép bạn viết ít mã hơn!

What is GEEK

Buddha Community

CODE VN

CODE VN

1643473323

Cách sử dụng ứng dụng Axios HTTP để yêu cầu dữ liệu JSON từ một API

Trong hướng dẫn này, bạn sẽ học cách sử dụng ứng dụng khách Axios HTTP để yêu cầu dữ liệu JSON từ một API. Sau đó, bạn sẽ học cách nhận phản hồi JSON, lặp qua dữ liệu mà phản hồi này chứa và đặt trạng thái của thành phần React của bạn dựa trên dữ liệu này

Bắt đầu nào!

Lưu ý: Hướng dẫn này giả định rằng bạn đang làm việc trong một ứng dụng React đã được tạo bằng cách sử dụng create-react-app.

Yêu cầu dữ liệu JSON

Phần đầu tiên của việc lặp qua một mảng JSON liên quan đến việc thực sự yêu cầu dữ liệu! Để yêu cầu dữ liệu từ một API, chúng tôi phải bắt đầu bằng cách sử dụng một ứng dụng khách HTTP. Trong hướng dẫn này, chúng tôi đã chọn Axios làm thư viện ứng dụng khách HTTP mà chúng tôi lựa chọn. Có rất nhiều lựa chọn thay thế! Tìm nạp là một ứng dụng khách gốc, tuyệt vời mà bạn có thể sử dụng nếu bạn đang cố gắng hạn chế số lượng phần phụ thuộc mà bạn đang sử dụng trong ứng dụng của mình.

Để tải xuống Axios, hãy điều hướng đến thư mục dự án gốc nơi chứa tệp của bạn và package.jsonchạy lệnh:. npm install --save axiosBây giờ bạn đã cài đặt Axios bên trong dự án React của mình và có thể bắt đầu sử dụng nó!

Trong đoạn mã dưới đây, bạn sẽ thấy lớp vỏ cơ bản của một SolarSystemthành phần. Công việc của thành phần này là yêu cầu danh sách các hành tinh từ máy chủ thông qua HTTP và sau đó hiển thị danh sách các Planetthành phần dựa trên phản hồi. Số lượng khí khổng lồ cũng sẽ cần được tính bằng cách lặp qua mảng JSON có trong phản hồi.

class SolarSystem Extends React.Component {
    constructor(props) {
        super(props);

        this.state = {
            planets: [],
            gasGiantsCount: 0
        }
    }

    componentDidMount() {
        ...
    }

    render() {
        ...
    }
}

Đầu tiên, bạn sẽ cần thiết lập planetstrạng thái của thành phần dựa trên danh sách các hành tinh được yêu cầu trong componentDidMountphương thức vòng đời. Phương componentDidMountthức vòng đời sẽ đảm bảo rằng dữ liệu của hành tinh chỉ được yêu cầu sau khi kết xuất ban đầu của SolarSystemthành phần. Điều này rất hữu ích vì bạn có thể hiển thị một màn hình tải đơn giản trong khi đợi yêu cầu hoàn tất.

Dưới đây là mã được cập nhật cho biết cách sử dụng Axios để thực hiện yêu cầu đối với API hành tinh riêng.

import axios from 'axios';

class SolarSystem Extends React.Component {
    constructor(props) {
        super(props);

        this.state = {
            planets: [],
            gasGiantsCount: 0
        }
    }

    async componentDidMount() {
        const { data: planets }  = await axios.get(this.props.planetApiUrl),
                  gasGiantsCount = planets.filter(planet => planet.isGasGiant).length;

        this.setState({ planets, gasGiantsCount });
    }

    render() {
        ...
    }
}

Wow, thật dễ dàng! Trong đoạn mã trên, trước tiên bạn đã nhập thư viện máy khách Axios HTTP. Sau đó, bạn đã đánh dấu componentDidMountlà một asyncchức năng. Điều này cho phép sử dụng awaittừ khóa để giải quyết Promisetrả về từ cuộc gọi đến axios.get.

Sau khi phản hồi được tải thành công, sau đó bạn có quyền truy cập vào đối tượng phản hồi Axios. Một trong những điều thú vị về Axios là nó tự động phân tích cú pháp JSON cho bạn! Bạn có thể truy cập JSON này trên datatrường của đối tượng phản hồi. Trong đoạn mã trên, chúng tôi sử dụng khả năng hủy cấu trúc đối tượng của JavaScript để lấy datatrường của đối tượng phản hồi và đổi tên nó thành planets. Trong trường hợp này, datatrường bao gồm mảng JSON đã được phân tích cú pháp của chúng ta.

Với quyền truy cập vào mảng JSON bạn cần, sau đó bạn lặp lại nó bằng cách sử dụng một trong các hàm nguyên mẫu Mảng của JavaScript. Trong trường hợp này, bạn có thể thấy rằng mã của bạn lặp lại trên các hành tinh và đếm số lượng khí khổng lồ trong hệ mặt trời.

Cuối cùng, bạn sử dụng setStatehàm để thiết lập trạng thái planetsgasGiantsCounttrạng thái của thành phần.

Với dữ liệu của bạn được yêu cầu, bây giờ đã đến lúc tải chế độ xem của bạn. Hãy nhớ rằng, thành phần này chỉ muốn hiển thị danh sách các Planetthành phần. Điều này có thể đạt được bằng cách thực hiện renderchức năng sau.

 ...

    render() {
        const { planets, gasGiantsCount } = this.state;

        const planetComponents = planets.map(planet => <Planet name={planet.name} type={planet.type} />);

        return (
            <div>
                <h2>{gasGiantsCount}</h2>
                <ul>{planetComponents}</ul>
            </div>
        )
    }
}

Làm việc với mảng JSON là một kỹ năng quan trọng khi tạo bất kỳ ứng dụng web nào. Trong React, bạn có thể làm việc với các mảng JSON dễ dàng bằng cách sử dụng một ứng dụng khách HTTP như Axios để giúp bạn với những thứ như phân tích cú pháp tự động của JSON. Các công cụ như Axios sẽ giúp công việc của bạn trở nên dễ dàng hơn bằng cách cho phép bạn viết ít mã hơn!

Wilford  Pagac

Wilford Pagac

1594289280

What is REST API? An Overview | Liquid Web

What is REST?

The REST acronym is defined as a “REpresentational State Transfer” and is designed to take advantage of existing HTTP protocols when used for Web APIs. It is very flexible in that it is not tied to resources or methods and has the ability to handle different calls and data formats. Because REST API is not constrained to an XML format like SOAP, it can return multiple other formats depending on what is needed. If a service adheres to this style, it is considered a “RESTful” application. REST allows components to access and manage functions within another application.

REST was initially defined in a dissertation by Roy Fielding’s twenty years ago. He proposed these standards as an alternative to SOAP (The Simple Object Access Protocol is a simple standard for accessing objects and exchanging structured messages within a distributed computing environment). REST (or RESTful) defines the general rules used to regulate the interactions between web apps utilizing the HTTP protocol for CRUD (create, retrieve, update, delete) operations.

What is an API?

An API (or Application Programming Interface) provides a method of interaction between two systems.

What is a RESTful API?

A RESTful API (or application program interface) uses HTTP requests to GET, PUT, POST, and DELETE data following the REST standards. This allows two pieces of software to communicate with each other. In essence, REST API is a set of remote calls using standard methods to return data in a specific format.

The systems that interact in this manner can be very different. Each app may use a unique programming language, operating system, database, etc. So, how do we create a system that can easily communicate and understand other apps?? This is where the Rest API is used as an interaction system.

When using a RESTful API, we should determine in advance what resources we want to expose to the outside world. Typically, the RESTful API service is implemented, keeping the following ideas in mind:

  • Format: There should be no restrictions on the data exchange format
  • Implementation: REST is based entirely on HTTP
  • Service Definition: Because REST is very flexible, API can be modified to ensure the application understands the request/response format.
  • The RESTful API focuses on resources and how efficiently you perform operations with it using HTTP.

The features of the REST API design style state:

  • Each entity must have a unique identifier.
  • Standard methods should be used to read and modify data.
  • It should provide support for different types of resources.
  • The interactions should be stateless.

For REST to fit this model, we must adhere to the following rules:

  • Client-Server Architecture: The interface is separate from the server-side data repository. This affords flexibility and the development of components independently of each other.
  • Detachment: The client connections are not stored on the server between requests.
  • Cacheability: It must be explicitly stated whether the client can store responses.
  • Multi-level: The API should work whether it interacts directly with a server or through an additional layer, like a load balancer.

#tutorials #api #application #application programming interface #crud #http #json #programming #protocols #representational state transfer #rest #rest api #rest api graphql #rest api json #rest api xml #restful #soap #xml #yaml

Top 10 API Security Threats Every API Team Should Know

As more and more data is exposed via APIs either as API-first companies or for the explosion of single page apps/JAMStack, API security can no longer be an afterthought. The hard part about APIs is that it provides direct access to large amounts of data while bypassing browser precautions. Instead of worrying about SQL injection and XSS issues, you should be concerned about the bad actor who was able to paginate through all your customer records and their data.

Typical prevention mechanisms like Captchas and browser fingerprinting won’t work since APIs by design need to handle a very large number of API accesses even by a single customer. So where do you start? The first thing is to put yourself in the shoes of a hacker and then instrument your APIs to detect and block common attacks along with unknown unknowns for zero-day exploits. Some of these are on the OWASP Security API list, but not all.

Insecure pagination and resource limits

Most APIs provide access to resources that are lists of entities such as /users or /widgets. A client such as a browser would typically filter and paginate through this list to limit the number items returned to a client like so:

First Call: GET /items?skip=0&take=10 
Second Call: GET /items?skip=10&take=10

However, if that entity has any PII or other information, then a hacker could scrape that endpoint to get a dump of all entities in your database. This could be most dangerous if those entities accidently exposed PII or other sensitive information, but could also be dangerous in providing competitors or others with adoption and usage stats for your business or provide scammers with a way to get large email lists. See how Venmo data was scraped

A naive protection mechanism would be to check the take count and throw an error if greater than 100 or 1000. The problem with this is two-fold:

  1. For data APIs, legitimate customers may need to fetch and sync a large number of records such as via cron jobs. Artificially small pagination limits can force your API to be very chatty decreasing overall throughput. Max limits are to ensure memory and scalability requirements are met (and prevent certain DDoS attacks), not to guarantee security.
  2. This offers zero protection to a hacker that writes a simple script that sleeps a random delay between repeated accesses.
skip = 0
while True:    response = requests.post('https://api.acmeinc.com/widgets?take=10&skip=' + skip),                      headers={'Authorization': 'Bearer' + ' ' + sys.argv[1]})    print("Fetched 10 items")    sleep(randint(100,1000))    skip += 10

How to secure against pagination attacks

To secure against pagination attacks, you should track how many items of a single resource are accessed within a certain time period for each user or API key rather than just at the request level. By tracking API resource access at the user level, you can block a user or API key once they hit a threshold such as “touched 1,000,000 items in a one hour period”. This is dependent on your API use case and can even be dependent on their subscription with you. Like a Captcha, this can slow down the speed that a hacker can exploit your API, like a Captcha if they have to create a new user account manually to create a new API key.

Insecure API key generation

Most APIs are protected by some sort of API key or JWT (JSON Web Token). This provides a natural way to track and protect your API as API security tools can detect abnormal API behavior and block access to an API key automatically. However, hackers will want to outsmart these mechanisms by generating and using a large pool of API keys from a large number of users just like a web hacker would use a large pool of IP addresses to circumvent DDoS protection.

How to secure against API key pools

The easiest way to secure against these types of attacks is by requiring a human to sign up for your service and generate API keys. Bot traffic can be prevented with things like Captcha and 2-Factor Authentication. Unless there is a legitimate business case, new users who sign up for your service should not have the ability to generate API keys programmatically. Instead, only trusted customers should have the ability to generate API keys programmatically. Go one step further and ensure any anomaly detection for abnormal behavior is done at the user and account level, not just for each API key.

Accidental key exposure

APIs are used in a way that increases the probability credentials are leaked:

  1. APIs are expected to be accessed over indefinite time periods, which increases the probability that a hacker obtains a valid API key that’s not expired. You save that API key in a server environment variable and forget about it. This is a drastic contrast to a user logging into an interactive website where the session expires after a short duration.
  2. The consumer of an API has direct access to the credentials such as when debugging via Postman or CURL. It only takes a single developer to accidently copy/pastes the CURL command containing the API key into a public forum like in GitHub Issues or Stack Overflow.
  3. API keys are usually bearer tokens without requiring any other identifying information. APIs cannot leverage things like one-time use tokens or 2-factor authentication.

If a key is exposed due to user error, one may think you as the API provider has any blame. However, security is all about reducing surface area and risk. Treat your customer data as if it’s your own and help them by adding guards that prevent accidental key exposure.

How to prevent accidental key exposure

The easiest way to prevent key exposure is by leveraging two tokens rather than one. A refresh token is stored as an environment variable and can only be used to generate short lived access tokens. Unlike the refresh token, these short lived tokens can access the resources, but are time limited such as in hours or days.

The customer will store the refresh token with other API keys. Then your SDK will generate access tokens on SDK init or when the last access token expires. If a CURL command gets pasted into a GitHub issue, then a hacker would need to use it within hours reducing the attack vector (unless it was the actual refresh token which is low probability)

Exposure to DDoS attacks

APIs open up entirely new business models where customers can access your API platform programmatically. However, this can make DDoS protection tricky. Most DDoS protection is designed to absorb and reject a large number of requests from bad actors during DDoS attacks but still need to let the good ones through. This requires fingerprinting the HTTP requests to check against what looks like bot traffic. This is much harder for API products as all traffic looks like bot traffic and is not coming from a browser where things like cookies are present.

Stopping DDoS attacks

The magical part about APIs is almost every access requires an API Key. If a request doesn’t have an API key, you can automatically reject it which is lightweight on your servers (Ensure authentication is short circuited very early before later middleware like request JSON parsing). So then how do you handle authenticated requests? The easiest is to leverage rate limit counters for each API key such as to handle X requests per minute and reject those above the threshold with a 429 HTTP response. There are a variety of algorithms to do this such as leaky bucket and fixed window counters.

Incorrect server security

APIs are no different than web servers when it comes to good server hygiene. Data can be leaked due to misconfigured SSL certificate or allowing non-HTTPS traffic. For modern applications, there is very little reason to accept non-HTTPS requests, but a customer could mistakenly issue a non HTTP request from their application or CURL exposing the API key. APIs do not have the protection of a browser so things like HSTS or redirect to HTTPS offer no protection.

How to ensure proper SSL

Test your SSL implementation over at Qualys SSL Test or similar tool. You should also block all non-HTTP requests which can be done within your load balancer. You should also remove any HTTP headers scrub any error messages that leak implementation details. If your API is used only by your own apps or can only be accessed server-side, then review Authoritative guide to Cross-Origin Resource Sharing for REST APIs

Incorrect caching headers

APIs provide access to dynamic data that’s scoped to each API key. Any caching implementation should have the ability to scope to an API key to prevent cross-pollution. Even if you don’t cache anything in your infrastructure, you could expose your customers to security holes. If a customer with a proxy server was using multiple API keys such as one for development and one for production, then they could see cross-pollinated data.

#api management #api security #api best practices #api providers #security analytics #api management policies #api access tokens #api access #api security risks #api access keys

Autumn  Blick

Autumn Blick

1601381326

Public ASX100 APIs: The Essential List

We’ve conducted some initial research into the public APIs of the ASX100 because we regularly have conversations about what others are doing with their APIs and what best practices look like. Being able to point to good local examples and explain what is happening in Australia is a key part of this conversation.

Method

The method used for this initial research was to obtain a list of the ASX100 (as of 18 September 2020). Then work through each company looking at the following:

  1. Whether the company had a public API: this was found by googling “[company name] API” and “[company name] API developer” and “[company name] developer portal”. Sometimes the company’s website was navigated or searched.
  2. Some data points about the API were noted, such as the URL of the portal/documentation and the method they used to publish the API (portal, documentation, web page).
  3. Observations were recorded that piqued the interest of the researchers (you will find these below).
  4. Other notes were made to support future research.
  5. You will find a summary of the data in the infographic below.

Data

With regards to how the APIs are shared:

#api #api-development #api-analytics #apis #api-integration #api-testing #api-security #api-gateway

An API-First Approach For Designing Restful APIs | Hacker Noon

I’ve been working with Restful APIs for some time now and one thing that I love to do is to talk about APIs.

So, today I will show you how to build an API using the API-First approach and Design First with OpenAPI Specification.

First thing first, if you don’t know what’s an API-First approach means, it would be nice you stop reading this and check the blog post that I wrote to the Farfetchs blog where I explain everything that you need to know to start an API using API-First.

Preparing the ground

Before you get your hands dirty, let’s prepare the ground and understand the use case that will be developed.

Tools

If you desire to reproduce the examples that will be shown here, you will need some of those items below.

  • NodeJS
  • OpenAPI Specification
  • Text Editor (I’ll use VSCode)
  • Command Line

Use Case

To keep easy to understand, let’s use the Todo List App, it is a very common concept beyond the software development community.

#api #rest-api #openai #api-first-development #api-design #apis #restful-apis #restful-api