Introduction to APIs with Python FastAPI

Moosa Ali
CodeX
Published in
8 min readOct 31, 2021

With the rise of the Software as a service (SaaS) model, APIs have become a very important part of software development. A short summary of the SaaS model is that software developers no longer need to create installable desktop applications, they simply create their applications on the web and deploy them on a web server and then expose the endpoints to the world using APIs.

But what is an API?

That's what we’re here to answer!

A Web-Application in a SaaS model has 3 integral parts.

  1. Client
  2. Server
  3. API

Number one should be self-explanatory. You, the user, are the client. The one using the product. The server is the actual software backend where all the processing happens. The client usually requests something from the server and the server then delivers the required information. Vice versa also occurs but more importantly, this delivery of data/information is where APIs come in. APIs are the bridge that connects the client to the server and carries out this seamless transfer of data from the client to the server and vice versa.

In even simpler words, imagine you are sitting in a restaurant and you order some food. The waiter takes your order to the cook and returns back with your food. In this scenario, you are the client (the user), the cook is the server (the back-end where the processing/cooking happens) and the waiter is the API (the bridge between you and the cook and the carrier of your food).

More about APIs

API stands for “Application Programming Interface”. I may have made an API sound quite simple but in reality, there are a lot more things involved.

Whenever you load a website, you are actually invoking the API of that website which then brings you the requested webpage. When you type in the domain name of the website you want to access and hit ‘Enter’, a request is sent to the server of that website with all the required information and in the response, the entire webpage is returned. This response is interpreted by your browser and it handles the loading of the webpage and all of its assets e.g. when you got to www.google.com, the HTML file of the website is returned to your browser. This HTML file contains information regarding what images to load or any other elements such as the search bar, the location of these assets on the webpage, and links to other webpages (buttons). Reading and displaying this file is your browser's responsibility and you don’t really need to worry about it.

data transfer illustration

Another way in which APIs are used is for the simple transfer of data. No fancy assets, no web pages, just plain simple data. There are several standardized formats for the transfer of data over APIs. The most common format is the JavaScript Object Notation (JSON) format. Other formats include XML, YAML, etc. This might be confusing for some people. Why would we request only data like this over the internet? But you use APIs like this more than you realize. When you use the weather application on your phone or on your computer, the application usually uses a third-party API to get the weather information. When you hit refresh, it sends a request to the API with some information such as your location or some other authorization parameter (If required by the API) and in the response, the API returns the weather information to the application in the JSON format, the application then formats the data according to its interface and displays it to you. This is just one use case of an API. Keep reading at the end I'll show you how you can build your own API and then see how we can request data from a third-party API.

Another important thing to mention here is that all of this communication is done using the HTTP protocol. HTTP is the standard protocol used for all sorts of communication over the web. HTTP has its own technicalities but we’re not here to talk about it so let's return to APIs.

There is one last thing that I need to mention before moving on to building an API; the API methods (HTTP methods).

There are a total of 4 actions that you can perform using an API.

  • GET
  • POST
  • PUT
  • DELETE

A GET request is like you (the client) asking the API to get something for you (a webpage or simply data in JSON format — server → client)

A POST method is used when you send some data to the server (client → server). This is done when you fill out a form when signing up for a social media app. The server stores the data that you send to it.

A PUT method is used when you wish to edit some data that already exists on the server. This method simply changes your existing data on the server.

A DELETE request — surprise surprise!! — sends a request to delete your data that exists on the server's database.

Building our own API — FastAPI

fastapi logo
source

Now that we’ve learned enough about APIs let's build one and test it out. for this tutorial we will need to install the following:

  • FastAPI
  • Uvicorn

FastAPI is an extremely light and fast framework for building APIs in python and Uvicorn is an ASGI server that FastAPI needs to run. These can be installed easily using the following commands.

pip install fastapi

and,

pip install uvicorn

Next, simply copy the following code into your IDE

Voila! your API is ready for testing.

Here we have created two different paths that can be accessed via the API. An API path is the URI that we use to access the endpoint. We have a base path denoted by “/” and our second path denoted by “/user”.The decorator above the functions denotes what sort of HTTP method is called (in our case both the functions generate a GET request).

Let's get it running. We need to start the uvicorn server in the terminal.

uvicorn run:app

In the above statement, ‘run’ is the name of the python file that has our code and ‘app’ is the name of the fastAPI object created in the file.

terminal response
terminal response

Now we simply need to go to our browser and type in localhost:8000/

This will trigger the base response and we see the following returned in our browser.

{"Response":"Default"}

just like we programmed!

FastAPI uses SwaggerUI that gives a nice little interface to test the API endpoints. For that, we need to go to the path localhost:8000/users

This will open the following page.

SwaggerUI
SwaggerUI

Here we see both our endpoints. Let's test the second endpoint and pull the information of the desired user.

Executing query for Muhammad Khan
Response Body
Response body

In the response body, we can see that we have data returned to us of the user that we sent as input.

That is the basics of how to build and test an API.

Testing service using postman

Before ending this article, I want to show you how companies utilize APIs to do business. For this, we will use the Postman application to get data from APIs.

For this, we will use the API provided by openweathermap.

To get the API key you have to create a free account and the API key will be sent to your email. The API key is used as an authorization parameter to ensure that data is sent to a registered user only.

When you open postman you will the following screen.

Postman Interface
postman interface

Click on the “Create a request” button on the right to create a GET request.

Query attributes

The endpoint and the required parameters are always provided in the APIs documentation. Above I have entered 2 parameters: 1) The city for which I want the weather data and the API key provided by openweathermap (The x’s are just a dummy entry for the screenshot, you WILL require an actual key).

Here’s what we get as a result of this request.

{"coord": {"lon": 74.3436,"lat": 31.5497},"weather": [{"id": 721,"main": "Haze","description": "haze","icon": "50n"}],"base": "stations","main": {"temp": 297.14,"feels_like": 296.8,"temp_min": 291.21,"temp_max": 297.14,"pressure": 1012,"humidity": 46},"visibility": 4000,"wind": {"speed": 0,"deg": 0},"clouds": {"all": 0},"dt": 1635693814,"sys": {"type": 1,"id": 7585,"country": "PK","sunrise": 1635643056,"sunset": 1635682484},"timezone": 18000,"id": 1172451,"name": "Lahore","cod": 200}

Theirs all the information you need (or not), depends on the requirement.

Conclusion

That ends with a brief introduction to APIs. In this article, we learned what APIs are, how to build one, and how different businesses utilize them to sell their products. In the modern world, APIs play a major role in web development and it is vital for every software developer to know their basics.

--

--

Moosa Ali
CodeX
Writer for

Blogger | Data Scientist | Machine Learning Engineer. For more content, visit: www.writersbyte.com. Support me on: ko-fi.com/moosaali9906