0
0
Rest APIprogramming~5 mins

Filtering by field values in Rest API

Choose your learning style9 modes available
Introduction

Filtering by field values helps you get only the data you want from a big list. It saves time and makes your results clear.

You want to see only users from a specific city in a user list.
You need to find products that cost less than $20 in an online store.
You want to get all orders placed after a certain date.
You want to show only active accounts in a system.
Syntax
Rest API
GET /resource?field=value

This is a simple way to ask the server for items where 'field' matches 'value'.

Multiple filters can be combined using & like: ?field1=value1&field2=value2

Examples
Get all users who live in London.
Rest API
GET /users?city=London
Get all products that cost exactly 20 units.
Rest API
GET /products?price=20
Get all orders that are shipped and placed on 1st June 2024.
Rest API
GET /orders?status=shipped&date=2024-06-01
Sample Program

This program asks the API for users who live in New York. It prints each user's name and city.

Rest API
import requests

# URL of the API
url = 'https://api.example.com/users'

# Filter to get users from New York
params = {'city': 'New York'}

response = requests.get(url, params=params)

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

Filtering depends on the API supporting query parameters.

Field names and values must match exactly what the API expects.

Some APIs support advanced filters like greater than or less than using special syntax.

Summary

Filtering helps get only the data you need from an API.

Use query parameters like ?field=value to filter results.

Check API docs to know which fields you can filter by.