0% found this document useful (0 votes)
15 views38 pages

Understanding RESTful APIs Explained

Uc3m university

Uploaded by

Luca Manzella
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views38 pages

Understanding RESTful APIs Explained

Uc3m university

Uploaded by

Luca Manzella
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

What is an API?

RESTful APIs References

REST API
Design of Telematic Systems

Miguel A Hombrados Herrera

Universidad Carlos III de Madrid

23/10/2023

Miguel A Hombrados Herrera Universidad Carlos III de Madrid


REST API 1 / 38
What is an API? RESTful APIs References

1 What is an API?

2 RESTful APIs

Miguel A Hombrados Herrera Universidad Carlos III de Madrid


REST API 2 / 38
What is an API? RESTful APIs References

APIs

API (web APIs)


• It stands for Application Programming Interface.
• It refers to software that implements a set of rules and
methods that allow clients to exchange data with remote
servers.
There are different types of architectures to design a web API:
• REST
• GraphQL
• SOAP

Miguel A Hombrados Herrera Universidad Carlos III de Madrid


REST API 3 / 38
What is an API? RESTful APIs References

APIs

URL: [Link]
Server domain [Link]
Path to resource /books/123
Resource id /123

In this context → END POINT = URL.


Miguel A Hombrados Herrera Universidad Carlos III de Madrid
REST API 4 / 38
What is an API? RESTful APIs References

1 What is an API?

2 RESTful APIs

Miguel A Hombrados Herrera Universidad Carlos III de Madrid


REST API 5 / 38
What is an API? RESTful APIs References

Example of popular RESTful APIs

Some examples:
• Twitter API
• Google Maps Platform APIs
• NASA APIs (free)
• Covid -19 data API (free)
• Open Weather Map API
For testing and development:
• JSON Placeholder
• Reqres

Miguel A Hombrados Herrera Universidad Carlos III de Madrid


REST API 6 / 38
What is an API? RESTful APIs References

API REST

• An API that follows the REST architecture is known as an


API REST or is described as RESTful.
• REST stands for Representational State Transfer.
• REST defines a set of rules of how HTTP should be handled
to exchange data. It defines specific properties that an API
must have to be considered RESTful.
• It uses HTTP to communicate with the API.
• Some popular examples of API based on the REST paradigm
are: S3 of AWS, Google Maps API, Twitter API, etc...

Miguel A Hombrados Herrera Universidad Carlos III de Madrid


REST API 7 / 38
What is an API? RESTful APIs References

API REST

REST APIs are characterized by:


1 Statesless: The requests to the server are self-contained and
do not require any additional information to fulfil the request.
The server does not retain any information of the client’s
context (state).
2 Client-server architecture: Client and server must operate
independently.
3 Uniform interface: Define a set of prinpiples that define a
standarized form of interaction between client and server.
Some of them include:
• The use of HTTPs standard methods (GET, POST, PUT,
DELETE) to manipulate resources;
• Unique identification of each resource with an URL;
• Follow specific conventions uniform accross the system to
name resources and to format data (XML or JSON).
Miguel A Hombrados Herrera Universidad Carlos III de Madrid
REST API 8 / 38
What is an API? RESTful APIs References

API REST

REST APIs are characterized by:


1 Cacheable: The data retrieved from the server should be
cacheable either by the client or by the server. This improves
independence between the client and server. 1 . If the response
is cacheable, it must be specified.
2 Layered system: The API can be deployed in a layered
system 2 without affecting its regular functioning.
3 Code on demand (optional): The server can send code to
the client to run.

If an API is designed following these guidelines, it can be


considered RESTful.
1
Here, caching means saving copies of the server responses.
2
One that is composed of several servers in a hierarchical structure
Miguel A Hombrados Herrera Universidad Carlos III de Madrid
REST API 9 / 38
What is an API? RESTful APIs References

API REST

Resources are organized into a set of unique URLs (URIs)

Miguel A Hombrados Herrera Universidad Carlos III de Madrid


REST API 10 / 38
What is an API? RESTful APIs References

HTTP requests

To perform requests to an API REST, you need to use the


standard HTTP methods.

HTTP methods Description


GET Method to retrieve data/resource.
POST Method to create a new resource/upload new data.
PUT 5 Method to update a resource.
PATCH Method to partially update a resource.
DELETE Method to remove a resource.
Table 1: Common HTTP request methods.

Miguel A Hombrados Herrera Universidad Carlos III de Madrid


REST API 11 / 38
What is an API? RESTful APIs References

HTTP status code


For every HTTP request, you will recieve a HTTP response from
the server, that gives you information about what happened with
the request. Within the response, you will find a status code:

Figure 1: HTTP response codes.

Examples: HTTP/1.1 200 OK or HTTP/1.1 404 Not


Miguel A Hombrados Herrera
Found
Universidad Carlos III de Madrid
REST API 12 / 38
What is an API? RESTful APIs References

HTTP: Luckily enough, with Python

• Fortunately, we will perform and handle HTTP requests using


Python, which simplifies the task.
• In particular, we will work with the Python module requests
to make HTTP requests for the client.

1 import requests

Miguel A Hombrados Herrera Universidad Carlos III de Madrid


REST API 13 / 38
What is an API? RESTful APIs References

GET example: NASA API


Let’s use a real REST API example: APOD
([Link] 3

3
You can browse for more NASA APIs at [Link]
Miguel A Hombrados Herrera Universidad Carlos III de Madrid
REST API 14 / 38
What is an API? RESTful APIs References

GET example: NASA API

1 import requests
2 # NASA APOD API endpoint
3 url = " https :// api . nasa . gov / planetary / apod "
4 params = {
5 " api_key " : " f a k e A P I k e y n u m b e r f o r t h e s a k e o f t h e e x a m p l e "
6 # It may contain other optional parameters
7 }
8 # GET request to https :// api . nasa . gov / planetary / apod
9 nasa_response = requests . get ( url , params = params )
10 if response . status_code == 200:
11 data = nasa_response . json ()
12 else :
13 # Failed to fetch data
14 print ( " Failed to fetch data . Status code : " ,
nasa_response . status_code )

Miguel A Hombrados Herrera Universidad Carlos III de Madrid


REST API 15 / 38
What is an API? RESTful APIs References

GET example with a real API: NASA API

• the api_key is included as a parameter in the request.


• In this example, we are sending a GET request resource to:
/planetary/apod
• The response is formatted in JSON.
• The data is fetched if the status code is 200 (OK).

Miguel A Hombrados Herrera Universidad Carlos III de Madrid


REST API 16 / 38
What is an API? RESTful APIs References

GET example with a real API: NASA API

After running the previous script:

You can access the header‘s response.

1 >>> nasa_response . headers

In a dictionary format that contains metadata, and useful information such as


the status code:

1 >>> print ( nasa_response . status_code )


2 200

We can verify the format type:

1 >>> response . headers [ ’ Content - Type ’]


2 ’ application / json ’

Miguel A Hombrados Herrera Universidad Carlos III de Madrid


REST API 17 / 38
What is an API? RESTful APIs References

GET example with a real API: NASA API

After running the previous script.

You can access the response’s payload:

1 >>> data = nasa_response . json ()


2 >>> data . keys ()
3 dict_keys ([ ’ date ’ , ’ explanation ’ , ’ hdurl ’ , ’
media_type ’ , ’ service_version ’ , ’ title ’ ,
’ url ’ ])

Which is returned as a Python dictionary. Or in raw bytes form:

1 >>> data = nasa_response . content


2 >>> type ( data )
3 < class ’ bytes ’ >

Miguel A Hombrados Herrera Universidad Carlos III de Madrid


REST API 18 / 38
What is an API? RESTful APIs References

GET example with a real API: NASA API

After running the previous script:

1 >>> data = nasa_response . json ()


2 >>> print ( data [ " explanation " ])
3 One year ago a Space Launch System rocket
left planet Earth on November 16 , 2022 at
1:47 am EST carrying the Orion spacecraft
on the Artemis I mission , the first
integrated test of NASA s deep space
exploration systems . Over an hour after
liftoff from Kennedy Space Center ‘ s
historic Launch Complex 39 B , one of Orion
‘ s external video cameras captured this
view of its new perspective from space .
In the foreground are Orion ‘ s Orb ...

Miguel A Hombrados Herrera Universidad Carlos III de Madrid


REST API 19 / 38
What is an API? RESTful APIs References

GET example with a real API: NASA API

After running the previous script:

1 >>> data = nasa_response . json ()


2 >>> print ( data [ " url " ])
3 ’ https :// apod . nasa . gov / apod / image /2311/
uhz1_1024 . jpg ’

Miguel A Hombrados Herrera Universidad Carlos III de Madrid


REST API 20 / 38
What is an API? RESTful APIs References

GET example with a real API: NASA API

Useful methods included in the response to remember:


• HTTP Header as Python dictionary: [Link]
• HTTP response status code: response.status_code
• Result in JSON format (if was returned in that format):
[Link]()

Miguel A Hombrados Herrera Universidad Carlos III de Madrid


REST API 21 / 38
What is an API? RESTful APIs References

GET example with a real API: NASA API

Miguel A Hombrados Herrera Universidad Carlos III de Madrid


REST API 22 / 38
What is an API? RESTful APIs References

GET example with a real APIe: NASA API

1 import requests
2 # NASA APOD API endpoint
3 url = " https :// api . nasa . gov / planetary / apod "
4 params = {
5 " api_key " : " f a k e A P I k e y n u m b e r f o r t h e s a k e o f t h e e x a m p l e " ,
6 " count " : 3
7 }
8 # GET request to https :// api . nasa . gov / planetary / apod
9 response = requests . get ( url , params = params )
10 if response . status_code == 200:
11 data = response . json ()
12 print ( " Title : " , data [0]. get ( " title " ) )
13 print ( " Explanation : " , data [0]. get ( " explanation " ) )
14 else :
15 # Failed to fetch data
16 print ( " Failed to fetch data . Status code : " , response .
status_code )

Miguel A Hombrados Herrera Universidad Carlos III de Madrid


REST API 23 / 38
What is an API? RESTful APIs References

GET example with a real API: NASA API

• Note that, in the previous example, we added the parameter


count as a new entry in the params dictionary.
• Be aware of the effects that the new parameters in the
response.
• In this example, the response has the form of a list of 3
dictionaries

Miguel A Hombrados Herrera Universidad Carlos III de Madrid


REST API 24 / 38
What is an API? RESTful APIs References

GET example with a real API: NASA API

Practice activity: NASA APOD API


Search [Link] and click "Generate API Key" to
sign up, and will receive the key in your email account. Now, from
Aula Global download the example script APOD_example.py
displayed before.
Goal: Modify the script to retrieve the link and today‘s picture.
a
A full documentation of the API can be found here

Miguel A Hombrados Herrera Universidad Carlos III de Madrid


REST API 25 / 38
What is an API? RESTful APIs References

An API for practicing

We will run some examples in: [Link]

Miguel A Hombrados Herrera Universidad Carlos III de Madrid


REST API 26 / 38
What is an API? RESTful APIs References

GET examples: jsonplaceholder

Fetch users:
1 import requests
2 api_url = " https :// js on placehold er . typicode . com / users "
3 response = requests . get ( api_url )
4 data = response . json ()

data = [Link]() returns a list with all users:


1 >>> type ( data )
2 list
3 >>> print ( len ( data ) )
4 10

Miguel A Hombrados Herrera Universidad Carlos III de Madrid


REST API 27 / 38
What is an API? RESTful APIs References

GET examples: jsonplaceholder


Fetch user #1:
1 import requests
2 api_url = " https :// js on placehold er . typicode . com / users /1 "
3 response = requests . get ( api_url )
4 data = response . json ()

data = [Link]() returns a single user (dictionary):


1 >>> type ( data )
2 dict
3 >>> print ( data )
4 { ’ id ’: 1 , ’ name ’: ’ Leanne Graham ’ , ’ username ’: ’

Bret ’ , ’ email ’: ’ Sincere@april . biz ’ , ’ address


’: { ’ street ’: ’ Kulas Light ’ , ’ suite ’: ’ Apt .
556 ’ , ’ city ’: ’ Gwenborough ’ , ’ zipcode ’: ’
92998 -3874 ’ , ’ geo ’: { ’ lat ’: ’ -37.3159 ’ , ’ lng ’
: ’ 81.1496 ’}} , ’ phone ’: ’ 1 -770 -736 -8031
x56442 ’ , ’ website ’: ’ hildegard . org ’ , ’ company
’: { ’ name ’: ’ Romaguera - Crona ’ , ’ catchPhrase ’:
Miguel A Hombrados Herrera
REST API
’ Multi - layered client - server neuralUniversidad
- net ’Carlos
, ’III de 28
Madrid
/ 38
What is an API? RESTful APIs References

GET examples: jsonplaceholder


Fetch nested resources (Example 1):
1 import requests
2 api_url = " https :// js on placehold er . typicode . com / users /1/
posts "
3 response = requests . get ( api_url )
4 data = response . json ()

The endpoint users/1/posts retrieves all the posts of user #1. This is
possible because the resources are nested.
1 >>> data [0]
2 { ’ userId ’: 1 ,
3 ’ id ’: 1 ,
4 ’ title ’: ’ sunt aut facere repellat provident
occaecati excepturi optio reprehenderit ’ ,
5 ’ body ’: ’ quia et suscipit \ nsuscipit recusandae
consequuntur expedita et cum \ nreprehenderit
molestiae ut ut quas totam \ nnostrum rerum est
autem sunt rem eveniet architecto ’}
Miguel A Hombrados Herrera Universidad Carlos III de Madrid
REST API 29 / 38
What is an API? RESTful APIs References

GET examples: jsonplaceholder


Fetch nested resources (Example 2):
1 import requests
2 api_url = " https :// js on placehold er . typicode . com / posts ? userId
=1 "
3 response = requests . get ( api_url )
4 data = response . json ()

The endpoint uposts?userId=1 retrieves all the posts of user #1. This is
possible because the resources are nested.
1 >>> data [0]
2 { ’ userId ’: 1 ,
3 ’ id ’: 1 ,
4 ’ title ’: ’ sunt aut facere repellat provident
occaecati excepturi optio reprehenderit ’ ,
5 ’ body ’: ’ quia et suscipit \ nsuscipit recusandae
consequuntur expedita et cum \ nreprehenderit
molestiae ut ut quas totam \ nnostrum rerum est
autem sunt rem eveniet architecto ’}
Miguel A Hombrados Herrera Universidad Carlos III de Madrid
REST API 30 / 38
What is an API? RESTful APIs References

GET examples: jsonplaceholderr

This example uses [Link] Routes:

Miguel A Hombrados Herrera Universidad Carlos III de Madrid


REST API 31 / 38
What is an API? RESTful APIs References

POST example: jsonplaceholder

1 import requests
2 api_url = " https :// js on placehold er . typicode . com / users "
3 user_data = {
4 " id " : 1 ,
5 " name " : " Potatoe " ,
6 " username " : " Garcia " ,
7 " email " : " Potatoe@april . biz " ,
8 }
9 response = requests . post ( api_url , json = user_data )
10 response . json ()

[Link]() shows the new user posted.


1 { ’ id ’: 11 ,
2 ’ name ’: ’ Potatoe ’ ,
3 ’ username ’: ’ Garcia ’ ,
4 ’ email ’: ’ Potatoe@april . biz ’}

By using [Link]() we are updating the server data base with a


new user in the server’s database. The user is generated as a dictionary
Miguel A Hombrados Herrera Universidad Carlos III de Madrid
in Python, and serialised using JSON.
REST API 32 / 38
What is an API? RESTful APIs References

POST example: jsonplaceholder


Alternatively:
1 import requests
2 import json
3 api_url = " https :// js on placehold er . typicode . com / users "
4 user_data = {
5 " id " : 1 ,
6 " name " : " Potatoe " ,
7 " username " : " Garcia " ,
8 " email " : " Potatoe@april . biz " ,
9 }
10 headers = { " Content - Type " : " application / json " }
11 response = requests . post ( api_url , data = json . dumps ( user_data )
, headers = headers )
12 response . json ()

1 { ’ id ’: 11 ,
2 ’ name ’: ’ Potatoe ’ ,
3 ’ username ’: ’ Garcia ’ ,
4 ’ email ’: ’ Potatoe@april . biz ’}
Miguel A Hombrados Herrera Universidad Carlos III de Madrid
REST API 33 / 38
What is an API? RESTful APIs References

POST example: jsonplaceholder

• Note that the POST method has associated a success code


201, not 200.
1 >>> response . status_code
2 201

Miguel A Hombrados Herrera Universidad Carlos III de Madrid


REST API 34 / 38
What is an API? RESTful APIs References

PUT example: jsonplaceholder


If you need to replace an user:
1 api_url = " https :// js on placehold er . typicode . com / users /10 "
2 user_data = {
3 " name " : " Potatoe " ,
4 " username " : " Garcia " ,
5 " email " : " Potatoe@april . biz " ,
6 }
7 response = requests . put ( api_url , json = user_data )
8 response . json ()

Note that the user to update was selected by extending the


url:"[Link]
1 { ’ id ’: 10 ,
2 ’ name ’: ’ Potatoe ’ ,
3 ’ username ’: ’ Garcia ’ ,
4 ’ email ’: ’ Potatoe@april . biz ’}

[Link]() shows the user updated.


Miguel A Hombrados Herrera Universidad Carlos III de Madrid
REST API 35 / 38
What is an API? RESTful APIs References

PATCH example: jsonplaceholder


If you need to partially update an user:
1 import requests
2 api_url = " https :// js on placehold er . typicode . com / users /10 "
3 new_data = { " email " : ’ my ne w em ai l@uc 3m . es ’}
4 response = requests . patch ( api_url , json = new_data )
5 response . json ()

The resource is partially updated. In particular, we changed the


field: email. The rest of the user data remains unchanged.
1 { ’ id ’: 10 ,
2 ’ name ’: ’ Clementina DuBuque ’ ,
3 ’ username ’: ’ Moriah . Stanton ’ ,
4 ’ email ’: ’ mynewemail@uc3m . es ’ ,
5 ’ address ’: { ’ street ’: ’ Kattie Turnpike ’ ,
6 .......

The status response is 200.


Miguel A Hombrados Herrera Universidad Carlos III de Madrid
REST API 36 / 38
What is an API? RESTful APIs References

DELETE example: jsonplaceholder

If you need to delete a user:


1 import requests
2 api_url = " https :// jsonplaceholder . typicode . com /
users /10 "
3 response = requests . delete ( api_url )

1 >>> response . json ()


2 {}

In this example, the status response is 200. But the convention is


204 : No Content

Miguel A Hombrados Herrera Universidad Carlos III de Madrid


REST API 37 / 38
What is an API? RESTful APIs References

References

[1] Real Python. API Integration in Python. https:


//[Link]/api-integration-in-python/.
Accessed on November 17, 2023.
[2] [Link]. [Link].
[Link] Accessed on November 17,
2023.
[3] MO Faruque Sarker and Sam Washington. Learning Python
Network Programming. Packt Publishing Ltd, 2015.

Miguel A Hombrados Herrera Universidad Carlos III de Madrid


REST API 38 / 38

You might also like