Understanding REST APIs
What is a REST API?
A REST API (Representational State Transfer Application Programming Interface) is a software architectural style that defines a set of rules and conventions for building and interacting with web services. It is widely used to create web services that can be accessed and consumed by clients over the internet.
REST APIs are based on the principles of the HTTP protocol, which is the foundation of the World Wide Web. They use standard HTTP methods like GET, POST, PUT, and DELETE to perform operations on resources exposed by the API. These resources can be in various formats, such as JSON (JavaScript Object Notation) or XML (eXtensible Markup Language).
The main purpose of a REST API is to provide a standardized and scalable way for different software systems to communicate and exchange data. Here are some reasons why we need REST APIs:
Client-Server Communication: REST APIs enable communication between client applications (such as web browsers, mobile apps, or other servers) and server-side applications. Clients can send HTTP requests to the API to retrieve or manipulate data stored on the server.
Platform Independence: REST APIs are platform-independent, meaning clients and servers can be developed using different programming languages and technologies as long as they adhere to the common rules and conventions of the REST architecture. We already have seen that we can use nearly any programming language for querying databases, and that is true for writing REST APIs too.
Scalability: REST APIs allow for the separation of concerns between the client and server. This allows each component to be developed, deployed, and scaled independently, making it easier to handle increased traffic or load on either side.
Statelessness: REST APIs are stateless, which means that each request from a client contains all the necessary information to be understood by the server. The server does not need to maintain any session state between requests, simplifying the architecture and making it more scalable.
Resourceful Operations: REST APIs expose resources as URLs (Uniform Resource Locators), and clients can perform various operations on these resources using standard HTTP methods. For example, a client can use a GET request to retrieve data, a POST request to create new data, a PUT request to update existing data, or a DELETE request to remove data.
Integration and Interoperability: REST APIs facilitate integration between different systems and applications. They provide a common language and interface for different software components to communicate and exchange data, allowing for the development of complex and distributed systems.
Creating a small REST API with Python
Now lets build a small REST API with Python. We will use the Flask library for creating this REST API. You can install Flask by running the command pip install Flask.
Now create a new file named api.pywith the following content:
from flask import Flask
app = Flask(__name__)
@app.route('/')
def hello_world():
return 'Hello, World!'
if __name__ == '__main__':
app.run()Execute the command python api.py. After that open a Browser and open the URL http://localhost:5000.
Now let's add another endpoint to our API by adding the following code to our Python script:
After that you need to restart the API by again running the command python api.py. Visit the URL http://localhost:5000/site. This is what you should see:
The API has just returned a HTML website. I have a little exercise for you now: Change the color of the h1 tag to blue (or another color you like) by modifying the HTML code that is returned by our endpoint. Use the style attribute of the h1 tag.
Querying the database and returning the result as a JSON object
Now we want to do something realy fancy. We want to query our database like we did it in the script we have written before and return the records as a JSON object, so that we can use them in a frontend web application.
Modify your Python script like this:
Restart the Python app, go to the browser and visit the following URL: http://localhost:5000/messages. This is what you should see:
Isn't that great? We have programmed an interface for our database that can now be used by webapps, mobile apps and any other software.
Writing the same REST API in JavaScript
Earlyer in this script I mentioned that you can use nearly any modern programming language for writing REST APIs. Let's proof that and write the same REST API in JavaScript.
First of all we need to create a new JavaScript project by running the command npm init like we did it before. You can also reuse your old project. Next we need to install some libraries. The first library is express, which is the equivalent to Flask in JavaScript. The second library is pg which we already used before. Run the command npm install express ng to install both libraries in your JavaScript project.
Next create a file named api.js with the following content:
Now start this REST API by running the following command: node api.js. This should make the REST API run on port 5000. Make sure you have terminated the Python REST API, otherwise this will cause errors, because only one API can listen to port 5000.
Now again visit http://localhost:5000, http://localhost:5000/site and http://localhost:5000/messages. Can you see any difference between the Python and the JavaScript REST API? Both are indistinguishable from a frontend's point of view.
Querying the API via Python scripts
We also can query REST APIs using programming languages. First let's do that with Python. Create a new file named query.py with the following content:
Now start the Python REST API and execute the script by running the command python query.py. Next terminate the Python REST API, start the JavaScript REST API and again run the python script. You should see no difference. This is great, we have written a software that is both written in Python and in JavaScript. Now let's write the API query in JavaScript too.
Create a file named query.js with the following content:
Before we can execute the script we need to install the Axios library, which is the equivalent to the requests library in Python by running the command npm install axios.
Now execute the script by running node query.js.
Adding new data to the database via the REST API
Next we need to create an endpoint for adding new records into the database. In python we can to this the following way:
In JavaScript we would do this the following way:
You also need to modify the creation of the app object in your file. Add the line app.use(express.json()); to your file before the endpoints. This line tells express that it should parse JSON objects utomatically.
Sending a POST request to the API
Now let's use Python and JavaScript again to send a POST request to our API to create a new record in our database table.
In Python you can do it the following way:
A JavaScript script that does the same looks like this:
Updating records via the REST API
Now it's time to update a record via the REST API. For updating records we are using PUT requests. In our Flask REST API we can add an endpoint for updating records in the following way:
In JavaScript the equivalend endpoint would look like this:
Now let's also write scripts that can query the REST API endpoints. In python this would look like the following way:
The equivalent code in JavaScript would look like this:
Delete records in the database via DELETE requests
Finally we want to delete existing records in our database. We add an endpoint to our REST API that will perform the SQL query for deleting records.
For our Python REST API the endpoint looks like this:
The equivalent JavaScipt endpoint looks like this:
The Python and JavaScript files that can perform DELETE requests look like this:
Python:
JavaScript:
Introducing a new tool for debugging our API
Now that we have seen how we can create REST APIs using Pthon and JavaScript and have seen how we can query the API using the same languages we can introduce a new tool called Postman. If we want to add more endpoints to our REST API writing scripts for querying and debugging the API is a little bit bulky. That why we introduce Postman.
Last updated