0
0
Rest APIprogramming~5 mins

Example requests and responses in Rest API

Choose your learning style9 modes available
Introduction

Example requests and responses show how to talk to a web service and what answers to expect. They help you understand how to use the service step-by-step.

You want to learn how to get data from a website using an API.
You need to send information to a server and see what it sends back.
You want to test if your API calls are working correctly.
You are building a program that talks to a web service and need examples.
You want to understand the format of data sent and received.
Syntax
Rest API
GET /resource HTTP/1.1
Host: example.com

Response:
HTTP/1.1 200 OK
Content-Type: application/json

{"key": "value"}

The request line shows the method (GET) and the resource path (/resource).

The response includes a status code (200 OK) and data in JSON format.

Examples
This example requests a list of users and gets back a JSON array with user details.
Rest API
GET /users HTTP/1.1
Host: api.example.com

Response:
HTTP/1.1 200 OK
Content-Type: application/json

[{"id":1,"name":"Alice"},{"id":2,"name":"Bob"}]
This example sends login details and receives a token to use for future requests.
Rest API
POST /login HTTP/1.1
Host: api.example.com
Content-Type: application/json

{"username":"user1","password":"pass123"}

Response:
HTTP/1.1 200 OK
Content-Type: application/json

{"token":"abc123xyz"}
This example deletes an item with ID 5 and gets a response with no content, meaning success.
Rest API
DELETE /items/5 HTTP/1.1
Host: api.example.com

Response:
HTTP/1.1 204 No Content
Sample Program

This program sends a GET request to get users, then prints each user's id and name if successful.

Rest API
import requests

# Example: Get user data from API
response = requests.get('https://api.example.com/users')

if response.status_code == 200:
    users = response.json()
    for user in users:
        print(f"User {user['id']}: {user['name']}")
else:
    print(f"Failed to get users: {response.status_code}")
OutputSuccess
Important Notes

Always check the response status code to know if the request worked.

Requests and responses usually use JSON format for easy reading and writing.

Headers like Content-Type tell the server what kind of data you send or expect.

Summary

Example requests show how to ask a web service for data or actions.

Example responses show what the server sends back after your request.

Using examples helps you learn and test APIs quickly and clearly.