API Flashcards
001 What is API?
Application Programming Interface
= a set of tools, procedures and protocols for apps and services to talk to other apps and services, so basically a communication bridge between them
3 main purposes:
- communication - it enables communication
- abstraction - it help software developers to streamline and shorten the application building process by eliminating frequently repeated program development processes
- standardization - there are industry standards and formats (SOAP, GraphQL, REST)
002 What is an API Endpoint?
An API endpoint refers to the touchpoints of interaction between an API and another system. An endpoint provides the location where an API accesses the resources they need.
An API works by requesting information from a server and then receiving a response after that. The communication channel that APIs use to send a request and specify where a given resource resides is what is known as an endpoint.
It plays an integral role in defining exactly where resources can be accessed and guarantee the proper functioning of any software that interacts with it.
003 What is an API call / request?
An API call, or API request, is a message sent to a server asking an API to provide a service or information. It travels from a client to an API endpoint, for example, a server. he server receives the API call, processes it, executes the request, and sends a response.
API calls are directed at a uniform resource identifier (URI). A URI is a standardized way to identify a resource, just as a phone number identifies a phone line. The identified resource could be a website, an application, a server, an email contact, or even a real-world item.
For web APIs, typically the URI is a uniform resource locator (URL). A URL is a type of URI for identifying Internet locations like a website or a server. A URL has to include the application layer protocol, such as HTTP, used to reach it. Webpage addresses are written as URLs, like “https://www.cloudflare.com/learning.” API endpoints are URLs too.
Most web APIs use HTTP, so that is included in the API endpoint’s URL. For example, the basic Cloudflare API endpoint is “https://api.cloudflare.com/client/v4/” (learn more). HTTP-based API calls use HTTP verbs (types of requests) like GET, POST, and PUT to denote what service or resource they need from the API endpoint.
004 How can API calls be used for an attack?
Like anything exposed to the Internet, APIs are vulnerable to attacks from a variety of sources. Attackers can use API calls in several ways to attack an API, including:
Denial-of-service (DoS) and distributed denial-of-service (DDoS) attacks: This type of attack denies service to other users of the API. Attackers can flood an API with API calls, or structure their API calls in such a way that they tie up the server for a long time.
Vulnerability exploits: Attackers can try sending API calls that take advantage of a flaw in the API to trick the server into revealing data it should not, perform in a way it is not designed for, or give them unauthorized access.
How to secure APIs from invalid API calls
The following strategies can help keep APIs secure:
- Understand and track API endpoints: Maintain an updated list of all API endpoints in production.
- Verify API clients: Authentication ensures that API calls come from a legitimate client. There are several ways to do this, but one of the most effective is mutual TLS, an authentication method in which each API endpoint verifies the other using public key cryptography.
- Validate API schema: An API’s schema is like its rules for usage. If an API call does not follow the schema, it may be a malicious attempt to exploit the API. API schema validation helps identify and block invalid API calls.
- Use DDoS mitigation: A DDoS mitigation provider blocks or absorbs excessive requests so that a server does not become overwhelmed. Cloudflare is one such
005 What is REST API?
A RESTful API — also referred to as a RESTful web service or REST API — is based on representational state transfer (REST) technology, an architectural style, and approach to communications often used in web services development.
REpresentational State Transfer:
REST, or REpresentational State Transfer, is an architectural style for providing standards between computer systems on the web, making it easier for systems to communicate with each other. REST-compliant systems, often called RESTful systems, are characterized by how they are stateless and separate the concerns of client and server. We will go into what these terms mean and why they are beneficial characteristics for services on the Web.
Separation of Client and Server
In the REST architectural style, the implementation of the client and the implementation of the server can be done independently without each knowing about the other. This means that the code on the client side can be changed at any time without affecting the operation of the server, and the code on the server side can be changed without affecting the operation of the client.
As long as each side knows what format of messages to send to the other, they can be kept modular and separate. Separating the user interface concerns from the data storage concerns, we improve the flexibility of the interface across platforms and improve scalability by simplifying the server components. Additionally, the separation allows each component the ability to evolve independently.
By using a REST interface, different clients hit the same REST endpoints, perform the same actions, and receive the same responses.
Statelessness
Systems that follow the REST paradigm are stateless, meaning that the server does not need to know anything about what state the client is in and vice versa. In this way, both the server and the client can understand any message received, even without seeing previous messages. This constraint of statelessness is enforced through the use of resources, rather than commands. Resources are the nouns of the Web - they describe any object, document, or thing that you may need to store or send to other services.
Because REST systems interact through standard operations on resources, they do not rely on the implementation of interfaces.
These constraints help RESTful applications achieve reliability, quick performance, and scalability, as components that can be managed, updated, and reused without affecting the system as a whole, even during operation of the system.
006 What is the general API request structure?
Communication between Client and Server in the REST architecture happens in such way, that clients send requests to retrieve or modify resources, and servers send responses to these requests.
Making requests:
REST requires that a client make a request to the server in order to retrieve or modify data on the server. A request generally consists of:
- an HTTP verb, which defines what kind of operation to perform
- a header, which allows the client to pass along information about the request
- a path to a resource
- an optional message body containing data
007 What are the 4 basic HTTP verbs?
There are 4 basic HTTP verbs we use in requests to interact with resources in a REST system:
POST — create a new resource
GET — retrieve a specific resource (by id) or a collection of resources
PUT — update a specific resource (by id)
DELETE — remove a specific resource by id
008 What is CRUD?
Create, Read, Update, Delete
When we are building APIs, we want our models to provide four basic types of functionality. The model must be able to Create, Read, Update, and Delete resources. Computer scientists often refer to these functions by the acronym CRUD. A model should have the ability to perform at most these four functions in order to be complete. If an action cannot be described by one of these four operations, then it should potentially be a model of its own.
The CRUD paradigm is common in constructing web applications, because it provides a memorable framework for reminding developers of how to construct full, usable models. For example, let’s imagine a system to keep track of library books. In this hypothetical library database, we can imagine that there would be a books resource, which would store book objects. Let’s say that the book object looks like this:
“book”: {
“id”: ,
“title”: ,
“author”: ,
“isbn”:
}
To make this library system usable, we would want to make sure there were clear mechanisms for completing the CRUD operations:
Create — This would consist of a function which we would call when a new library book is being added to the catalog. The program calling the function would supply the values for “title”, “author”, and “isbn”. After this function is called, there should be a new entry in the books resource corresponding to this new book. Additionally, the new entry is assigned a unique id, which can be used to access this resource later.
Read — This would consist of a function which would be called to see all of the books currently in the catalog. This function call would not alter the books in the catalog - it would simply retrieve the resource and display the results. We would also have a function to retrieve a single book, for which we could supply the title, author, or ISBN. Again, this book would not be modified, only retrieved.
Update — There should be a function to call when information about a book must be changed. The program calling the function would supply the new values for “title”, “author”, and “isbn”. After the function call, the corresponding entry in the books resource would contain the new fields supplied.
Delete — There should be a function to call to remove a library book from the catalog. The program calling the function would supply one or more values (“title”, “author”, and/or “isbn”) to identify the book, and then this book would be removed from the books resource. After this function is called, the books resource should contain all of the books it had before, except for the one just deleted.
009 How do we use CREATE function in the REST environment?
Create
To create resources in a REST environment, we most commonly use the HTTP POST method. POST creates a new resource of the specified resource type.
For example, let’s imagine that we are adding a new food item to the stored list of dishes for this restaurant, and the dish objects are stored in a dishes resource. If we wanted to create the new item, we would use a POST request:
Request:
POST http://www.myrestaurant.com/dishes/
Body -
{
“dish”: {
“name”: “Avocado Toast”,
“price”: 8
}
}
This creates a new item with a name value of “Avocado Toast” and a price value of 8. Upon successful creation, the server should return a header with a link to the newly-created resource, along with a HTTP response code of 201 (CREATED).
Response:
Status Code - 201 (CREATED)
Body -
{
“dish”: {
“id”: 1223,
“name”: “Avocado Toast”,
“price”: 8
}
}
From this response, we see that the dish with name “Avocado Toast” and price 8 has been successfully created and added to the dishes resource.
010 How do we use READ function in the REST environment?
Read
To read resources in a REST environment, we use the GET method. Reading a resource should never change any information - it should only retrieve it. If you call GET on the same information 10 times in a row, you should get the same response on the first call that you get on the last call.
GET can be used to read an entire list of items:
Request:
GET http://www.myrestaurant.com/dishes/
Response: Status Code - 200 (OK)
Body -
{
“dishes”: [
{
“id”: 1,
“name”: “Spring Rolls”,
“price”: 6
},
{
“id”: 2,
“name”: “Mozzarella Sticks”,
“price”: 7
},
…
{
“id”: 1223,
“name”: “Avocado Toast”,
“price”: 8
},
{
“id”: 1224,
“name”: “Muesli and Yogurt”,
“price”: 5
}
]
}
GET requests can also be used to read a specific item, when its id is specified in the request:
Request:
GET http://www.myrestaurant.com/dishes/1223
Response: Status Code - 200 (OK)
Body -
{
“id”: 1223,
“name”: “Avocado Toast”,
“price”: 8
}
After this request, no information has been changed in the database. The item with id 1223 has been retrieved from the dishes resource, and not modified. When there are no errors, GET will return the HTML or JSON of the desired resource, along with a 200 (OK) response code. If there is an error, it most often will return a 404 (NOT FOUND) response code.
011 How do we use UPDATE function in the REST environment?
Update
PUT is the HTTP method used for the CRUD operation, Update.
For example, if the price of Avocado Toast has gone up, we should go into the database and update that information. We can do this with a PUT request.
Request:
PUT http://www.myrestaurant.com/dishes/1223
Body -
{
“dish”: {
“name”: “Avocado Toast”,
“price”: 10
}
}
This request should change the item with id 1223 to have the attributes supplied in the request body. This dish with id 1223 should now still have the name “Avocado Toast”, but the price value should now be 10, whereas before it was 8.
Response: Status Code - 200 (OK)
Body -
{
“dish”: {
“name”: “Avocado Toast”,
“price”: 10
}
}
The response includes a Status Code of 200 (OK) to signify that the operation was successful. Optionally, the response could use a Status Code of 204 (NO CONTENT) and not include a response body. This decision depends on the context.
012 How do we use DELETE function in the REST environment?
Delete
The CRUD operation Delete corresponds to the HTTP method DELETE. It is used to remove a resource from the system.
Let’s say that the world avocado shortage has reached a critical point, and we can no longer afford to serve this modern delicacy at all. We should go into the database and delete the item that corresponds to “Avocado Toast”, which we know has an id of 1223.
Request:
DELETE http://www.myrestaurant.com/dishes/1223
Such a call, if successful, returns a response code of 204 (NO CONTENT), with no response body. The dishes resource should no longer contain the dish object with id 1223.
Response: Status Code - 204 (NO CONTENT)
Body - None
Calling GET on the dishes resource after this DELETE call would return the original list of dishes with the {“id”: 1223, “name”: “Avocado Toast”, “price”: 10} entry removed. All other dish objects in the dishes resource should remain unchanged. If we tried to call a GET on the item with id 1223, which we just deleted, we would receive a 404 (NOT FOUND) response code and the state of the system should remain unchanged.
Calling DELETE on a resource that does not exist should not change the state of the system. The call should return a 404 response code (NOT FOUND) and do nothing.
013 What is HTTP Keep-Alive?
HTTP keep-alive, a.k.a., HTTP persistent connection, is an instruction that allows a single TCP connection to remain open for multiple HTTP requests/responses.
By default, HTTP connections close after each request. When someone visits your site, their browser needs to create new connections to request each of the files that make up your web pages (e.g. images, Javascript, and CSS stylesheets), a process that can lead to high page load times.
Enabling the keep-alive header allows you to serve all web page resources over a single connection. Keep-alive also reduces both CPU and memory usage on your server.
014 How to enable the Keep-Alive Header?
In the event that keep-alive is not enabled on your server, it can be turned on by adding the following code to your .htaccess file:
Header set Connection keep-alive>
Within the ‘Connection keep-alive’ header, the following two directives can affect its functionality:
- MaxKeepAliveRequests – This directive sets the maximum number of requests for every keep-alive connection. When determining this figure, it’s important to take into account the number of files on your website that a user might want to access.
- KeepAliveTimeout – This directive sets the time that a server should wait for user requests before a new TCP connection needs to be established. This figure should be set according to how frequently your website is visited, i.e., sites with high traffic volumes will want to have a large timeout value to limit the number of TCP connection requests.
015 What are the benefits of connection Keep Alive?
The HTTP keep-alive header maintains a connection between a client and your server, reducing the time needed to serve files. A persistent connection also reduces the number of TCP and SSL/TLS connection requests, leading to a drop in round trip time (RTT).
Establishing a TCP connection first requires a three-way handshake – a mutual exchange of SYN and ACK packets between a client and server before data can be transmitted. Using the keep-alive header means not having to constantly perform this process. This results in:
Network resource conservation – It’s less taxing on network resources to use a single connection per client.
Reduced network congestion – Reducing the number of TCP connections between your servers and clients can lead to a drop in network congestion.
Decreased latency – Reducing the number of three-way handshakes can lead to improved site latency. This is especially true with SSL/TLS connections, which require additional round-trips to encrypt and verify connections.