-
Notifications
You must be signed in to change notification settings - Fork 0
(B). Basic REST API Overview
In this section, we will build our first REST API; the REST API will receive requests from a client, such as a web application or a mobile app, and it will respond with some data.
As we've learned, the significant benefit of having a REST API is that multiple applications can make requests to the same API and share resources, such as a database. So, when a client sends a request, such as one, to create a store, our API will create a store and put it in the database. Then, multiple clients can get information about that same store.
- Create stores, each with a
name
and a list of stockeditems
. - Create an item within a store, each with a
name
and aprice
. - Retrieve a list of all stores and their items.
- Given its
name
, retrieve an individual store and all its items. - Given a store
name
, retrieve only a list of item within it.
Here is the set of endpoints (or URLs) our API will provide; clients can use them to access and interact with the resources the API exposes.
If we get a POST request to
/store
and the request includes the name of the store we want to create, the API will create a store and respond with the store information. The response will contain the name of the store we just created and a list of items for that store, which will be initially empty.
Request:
POST /store {"name": "My Store"}
Response:
{"name": "My Store", "items": []}
When we create items, we will receive a POST request to
/store/
the store name; here, it'sMy Store/item
. It will receive thename
andprice
of the item we want to create. And it will create this item inside the store. Then it will respond with the item that it created.
Request:
POST /store/My Store/item {"name": "Chair", "price": 175.50}
Response:
{
"name": "Chair",
"price": 175.50
}
To retrieve all the stores and all their items, we will send a
GET
request to/store
. And the API responds with an object or a dictionary containing the store's key and a list. And inside this list, there are a bunch of dictionaries. Each dictionary represents one store that has the name and the items. Here, we would have a list of items with a single dictionary, which is the item we already created.
Request:
GET /store
Response:
{
"stores": [
{
"name": "My Store",
"items": [
{
"name": "Chair",
"price": 175.50
}
]
}
]
}
If you want to get a particular store, you can make a
GET
request,/store/
, and then the store's name; that will send the information for a single store.
Request:
GET /store/My Store
Response:
{
"name": "My Store",
"items": [
{
"name": "Chair",
"price": 175.50
}
]
}
If you want to get the items within a store, you can do
/store/
the store name and then the item. And that will get you the list of items within the store.
Request:
GET /store/My Store/item
Response:
[
{
"name": "Chair",
"price": 175.50
}
]