0
0
Rest APIprogramming~5 mins

First API request and response in Rest API

Choose your learning style9 modes available
Introduction

APIs let programs talk to each other over the internet. Making your first API request helps you get data or send information from one program to another.

You want to get weather information from a weather service.
You want to send a message using a chat app's API.
You want to get user details from a social media platform.
You want to check the latest news from a news API.
You want to send data to a server to save it.
Syntax
Rest API
GET /endpoint HTTP/1.1
Host: api.example.com

This is a simple GET request format to ask for data from an API.
You usually need to include the API's host and the specific endpoint you want.
Examples
This asks the API to send a list of users.
Rest API
GET /users HTTP/1.1
Host: api.example.com

This sends a message with the text "Hello!" to the API.
Rest API
POST /messages HTTP/1.1
Host: api.example.com
Content-Type: application/json

{"text": "Hello!"}
Sample Program

This Python program makes a GET request to a test API to get a post with ID 1. It prints the status code and the data received.

Rest API
import requests

response = requests.get('https://jsonplaceholder.typicode.com/posts/1')
print('Status code:', response.status_code)
print('Response body:', response.json())
OutputSuccess
Important Notes

Always check the status code to see if your request worked (200 means success).

API responses are often in JSON format, which is easy to read and use in programs.

Use tools like Postman or browser DevTools to test API requests before coding.

Summary

APIs let programs share data by sending requests and getting responses.

Your first API request usually asks for data using a GET method.

Check the response status and data to make sure your request worked.