Getting Started With FastAPI

Abhishek Bose
Sep 6, 2020 · 5 min read

Rest APIs are beautiful pieces of software that enable applications to communicate with a database or with other software very effectively.

The kind of operations which you can perform are as follows are GET, POST, PUT, DELETE, TRACE, etc. The GET method is generally used for fetching some information from the backend. For example, if an app (web/phone) wants to fetch some information from the database, it will use the GET method. POST is used for creating new information. PUT is used for updating already existing records. DELETE, as the name suggests is used for the deletion of records in a database. The TRACE method is used for debugging purposes and used for checking what is received on the other end when a request is invoked.

Since ages FLASK has been the most famous python framework for creating REST services. It is easy to use and deploy and can be used effectively for creating production-grade microservices.

FLASK has its own set of disadvantages though. It is not suitable for large applications. No admin site support. Does not provide any authentication mechanism. Lacks the powerful ORM tool which allows CRUD operations with any database.

Ref: https://github.com/tiangolo/fastapi

Recently, some extremely good men out there have come up with brand new framework for Python to mitigate the issues mentioned above, called FastAPI

https://github.com/tiangolo/fastapi (repo link)

The makers and users of this framework claim that the APIs created from FastAPI are literally very fast. As fast as Node and Go based Rest APIs.

The official FastAPI website has multiple testimonials from developers working in major tech firms proving the effectiveness of this framework.

Without much ado let’s go ahead and write a few APIs using this brand new framework and see it in action.

Use pip to install fastapi and uvicorn as shown in fig 1 below. Uvicorn is ASGI server which we will be using for production.

Fig1: Installing fastapi and uvicorn using pip

We will go ahead and write a simple GET API and check the response from our browser. We will also explore the admin panel for FastAPI.

Fig 2: GET api which returns a string

As shown in Fig 2, we have defined a route called “/” which returns a static response.

Start the uvicorn server using the command shown in Fig 3 and you should see the info showing that the server is up and running

Fig 3: Uvicorn server started

Hitting the address http://127.0.0.1:8000 in our browser window returns the expected response as shown in Fig 4.

Fig 4: Default GET response

One of the most coolest features of FastAPI is the internal automatic API documentation.Visiting http://server_IP:Port/docs#/ opens up this cool dashboard which can be used to view and test out the APIs created (Fig 5). When running on a local machine the URL would be http://127.0.0.1:8000/docs#/

Fig 5: Dashboard to list and debug APIs

Now we will create a POST api which let’s us upload a CSV file and convert it to json. That json is then returned in the API reponse

First we will go head and write the functions needed to convert bytes to string and then convert that to json using pandas Dataframe. Fig 6 shows the two functions which will be needed for this task. Inside convertBytesToString , we call parse_csv which converts our pandas dataframe to a json file.

Fig 6: Parsing our CSV and converting it to json

Next, we will put down our POST method to upload the CSV file from the client-end and receive a json from the server.

Fig 7 demonstrates the process of creating this API.

On the top we import the UploadFile and File class from fastapi. UploadFile is a very powerful class and actually presents the file in a spooledfile format. Spooled files are actually temporary files stored in memory until the file size exceeds the max size specified. As result spooled files are extremely fast to work on and reduce the I/O needed for files on disc.

Next we import the convertBytesToString function from our parse_csv file.

Fig 7: parsecsv post api to convert csv to json

We declare a POST method called “/csv/” which has the parsecsv method defined to parse our csv file. The parameter is a file of type UploadFile.

As you can see that we have used the async and await keyword to asure concurrency in our API methods. We will talk more about the usage of these types in later posts.

The variable to json_string receives the parsed csv file which is returned in the API response.

Now let’s go ahead and test out our newly created API.

Navigate to the FastAPI api debugging link mentioned top. You should see your newly created API listed (Fig 8) , along with the API which was previously created (getName)

Fig 8: Post API on our API debugging dashboard

In order to test the API out we will have to create a dummy csv file. I have created a csv called grades.csv (Fig 9) .This will be used for our testing.

Fig 9: Dummy csv for testing

Let’s upload our csv file and check the response on the dashboard. By clicking on our newly created API, you should a browse button, which prompts the user to upload a file. The Execute button below that hits the API with the the correct params (Fig 10).

Fig 10: Upload the file using the browse button. Hit execute to test out your new API

Fig 11 shows the result on hitting the Execute button. The Response body shows the json created from the csv file. I agree the json could be formatted in a much better way 😄, but the goal to parse the csv successfully using FastAPI was achieved.

I will be posting more blogs with FastAPI as the major tool and will be creating REST services for AI purposes as well.

Thank for reading. Cheers!!

The Startup

Get smarter at building your thing. Join The Startup’s +799K followers.

Abhishek Bose

Written by

Engineering at NAYAN Technologies. On a quest for technology.

The Startup

Get smarter at building your thing. Follow to join The Startup’s +8 million monthly readers & +799K followers.

Abhishek Bose

Written by

Engineering at NAYAN Technologies. On a quest for technology.

The Startup

Get smarter at building your thing. Follow to join The Startup’s +8 million monthly readers & +799K followers.

Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore

If you have a story to tell, knowledge to share, or a perspective to offer — welcome home. It’s easy and free to post your thinking on any topic. Write on Medium

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store