Introduction
Suppose you're using a weather app on your phone. If you want to know the weather in a specific city, let's say "Mumbai." You type "Mumbai" in the search bar and tap the search button. The app uses something called REST API to get the weather data for Mumbai. The app then shows you the current temperature, humidity, wind speed, and other weather details for Mumbai that too in a very quick and seamless fashion.
In simple terms, the REST API helps the weather app talk to a weather service and get the information you need. It's like asking a friend to find out the weather for you and getting the answer right away.
API stands for Application Programming Interface. It is a set of rules and protocols that allows different software applications to communicate and interact with each other.
REST stands for Representational State Transfer. It is a set of architectural constraints, that developers follow when they create their API. It influences the design and structure of an API.
REST API is a specific type of API that follows the principles of the REST architectural style.
RESTful web services are designed around the principles of Representational State Transfer (REST). RESTful web services are very popular because they are light weight, highly scalable and maintainable and are very commonly used to create APIs for web-based applications.
The Endpoint
The endpoint (or route) is the url you request for. An API endpoint is basically a fancy word for URL of a server or service.
For Twitter API , the root end point is https://api.twitter.com
https://example.com/api
- In this case, the root endpoint is located at the /api
path of the domain example.com
.
Root endpoints are typically used to get a list of all the resources in the API, or to get information about a specific resource. For example, the following request would get a list of all the posts in the WordPress REST API:
Code snippet
GET /wp-json/wp/v2/posts
The following request would get information about the user with the ID of 123 in the Google Cloud Platform API:
GET /api/v1/users/123
To get a list of all posts tagged under “React” on XYZ, you navigate to
https://www.XYZ.com/tag/React/
Here, https://www.XYZ.com/
is the root-endpoint and tag/React/
is the path
To understand what options are available to you, you should review the API documentation. By studying the documentation, you can gain insights into the available paths or routes you can take to integrate the API into your project and achieve the desired functionality.
Also if we see colon ":" in a path, then it refers to a variable and should be replaced with the actual values.
Query parameters are additional key-value pairs that are included at the end of a URL in a REST API request. They provide a way to modify the request and specify certain conditions or criteria for the desired data. Query parameters are commonly used to filter, sort, and paginate the results returned by the API.
Filtering
Query parameters can be used to filter the results based on specific criteria.
/users?status=active
: Retrieves only active users. /products?category=electronics&price=less_than_1000
: This request would return a JSON response that contains a list of products in the Electronics category that have a price less than $1000. Notice that each parameter pair is then separated with an ampersand (&
):
Sorting
Query parameters can be used to define the sorting order of the results. You can specify the field to sort on and the direction (ascending or descending).
/api/products?sort=price&order=asc
The request would get a list of all the products and sort the results by price in ascending order. The default order is ascending, so the order
query parameter is not mandatory in this case.
Pagination
When dealing with large datasets, query parameters are often used for pagination. You can specify the page number and the number of items per page to retrieve chunks of data incrementally.
/api/products?page=2&limit=20
The request would get the second page of 20 products from a REST API. The limit
query parameter is used to specify the number of products that you want to get per page. The default page number is 1, and the default limit is 10.
Searching
Query parameters can be used to perform search operations on the API. You can pass keywords or search terms to retrieve results that match the provided query.
/api/products?search=phone
:the request would get a list of products that match the search term "phone". The search
query parameter is used to specify the search term that you want to use to filter the results.
Curl:
Testing Endpoints With Curl
Curl is a powerful command-line tool for making HTTP requests. You can use it to test API endpoints by sending requests and examining the responses. You can send a request with any programming language but API documentations are normally written with reference to cURL. So lets us understand about Curl.
Check curl is installed in your system or not using
curl --version
.If it is not installed, download it from hereThen type curl followed by the endpoint of the API you are requesting for. For example:
curl https://api.github.com
cURL with query params
If you wish to include query parameters with cURL, make sure you prepend a backslash (\
) before the ?
and =
characters. This is because ?
and =
are special characters in the command line. You need to use \
before them for the command line to interpret them as normal characters:
curl https://jsonplaceholder.typicode.com/posts\?userId\=5
curl <options> <url>
Some of the most commonly used options are:
X or --request - HTTP method to be used
i or --include - Include the response headers
d or --data - The data to be sent to the API
H or --header- Any additional headers to be sent
HTTP Methods:
The method is the type of request you send to the server:
GET
POST
PUT
DELETE
These methods provide meaning for the request you’re making. They are used to perform four possible actions:
Create
,Read
,Update
andDelete
(CRUD).CREATE
->POST
READ
->GET
UPDATE
->PUT
DELETE
->DELETE
You can set the request method in cURL by writing
-X
or--request
, followed by the request method. This command below tries to create a repository via cURL:curl -X POST https://api.github.com/user/repos
However we get this message :
The response received above indicates that authentication is required to perform the requested action. In this case, we are trying to create a repository for the authenticated user on GitHub.
However, to successfully create a repository using the GitHub API, you need to provide authentication credentials in your request. GitHub uses OAuth 2.0 for authentication and requires an access token to authorize API requests.
HEADERS
Headers are used to provide information to both the client and server. It can be used for many purposes, such as authentication and providing information about the body content.
HTTP headers consist of a name-value pair separated by a colon (:). The header name and value are typically separated by a single space. Here's an example:
Header-Name: Header Value
In this example, "Header-Name" is the name of the header, and "Header Value" is the corresponding value.
Headers can be included in both the request and response messages in an HTTP transaction. They provide additional information that helps the client and server understand and process the request or response correctly.
Some common headers include:
Content-Type
: Specifies the type and format of the data in the request or response body.Authorization
: Provides authentication credentials for the request.User-Agent
: Identifies the client software or user agent making the request.Accept
: Indicates the media types that are acceptable for the response.Location
: Specifies the URL to redirect to in a response.For more information regarding headers check:
You can use the curl
command to make requests to the GitHub API to access different resources. For example, the following command will make a GET request to the URL for the list of issues for the current user:
curl -H "Content-Type: application/json" https://api.github.com/issues
The Data
The data (sometimes called “body” or “message”) contains information you want to be sent to the server. This option is only used with POST
, PUT
, PATCH
or DELETE
requests.
To send data through cURL, you can use the -d
or --data
option:
curl -X POST <URL> -d property1=value1
To send multiple data fields, you can create multiple -d
options:
curl -X POST <URL> -d property1=value1 -d property2=value2
Basic Authentication
Since POST
, PUT
, PATCH
and DELETE
requests alter the database, developers almost always put them behind an authentication wall.
This option allows you to specify the username and password directly in the command.
A convenient way to perform Basic Authentication with Curl is by using the -u
option
Here's the syntax to use the -u
option with Curl:
curl -u username:password https://api.example.com/endpoint
Replace username
with your actual username and password
with your actual password. The -u
option takes care of encoding the credentials in the required format (Base64) and including them in the Authorization
header.
When using the -u
option, Curl will automatically generate the appropriate Authorization
header with the encoded credentials.
However, the Basic Authentication with plaintext credentials in the command line may pose security risks, especially if the command is stored in a history file or logged. Consider more secure authentication methods like:
OAuth 2.0
JSON Web Tokens (JWT)
API Keys with HMAC (Hash-based Message Authentication Code)
HTTP response codes or HTTP status messages
curl -v -H "Content-Type: application/json" https://api.github.com/issues
You can debug the status of a response with the verbose option (
-v
or--verbose
) or the head option (-I
or--head
).You can obtain more information about the response, including the HTTP status code, response headers, and other details. These options are helpful for debugging and troubleshooting purposes, allowing you to analyze the interaction between the client and server in more detail.
Here are some commonly encountered HTTP status codes grouped by their respective ranges:
Informational responses (1xx):
100 Continue
101 Switching Protocols
Successful responses (2xx):
200 OK
201 Created
204 No Content
Redirection messages (3xx):
300 Multiple Choices
301 Moved Permanently
302 Found
304 Not Modified
Client error responses (4xx):
400 Bad Request
401 Unauthorized
403 Forbidden
404 Not Found
409 Conflict
Server error responses (5xx):
500 Internal Server Error
501 Not Implemented
503 Service Unavailable
504 Gateway Timeout
If you want to check out more status codes: click here
I hope you enjoyed this article, and if you have any questions, comments, or feedback, then feel free to comment here or reach out via Twitter.
Feel free to connect on Linkedin, Twitter, Instagram
Pic credits: mannhowie.com, Simplilearn