Skip to main content

How to Create a REST API with Python and FastAPI Framework

Welcome! Let's take a look at "How to create a REST API with Python and FastAPI framework"๐Ÿš€.

API is essential for building a multi-layer application structure, so choosing the right framework for your API can make the performance of your application robust.

FastAPI is a modern, fast (high-performance), a web framework for building APIs with Python 3.6+ based on standard Python type hints (source). It is written in Python with Starlette and Pydantic as a base. Big bull companies like Microsoft, Uber, Netflix, etc. have already started using FastAPI.

One of the reasons why I like FastAPI is because of the automatic interactive documentation. It will auto-generate Swagger documentation (not only Swagger but also Redoc) for you without any trouble of writing additional code.

Let's Begin Coding...

Prerequisites:

  • Python 3.6+ (and how to use it๐Ÿ˜‚)
  • pip (if already installed then ignore)

Install FastAPI from pypi using pip, you also need to install an ASGI server.

 pip install fastapi 

 pip install uvicorn[standard] 

If you are familiar with the flask framework then it is very much similar to it, and if you are not then no worries. Once both are installed create a file app.py with the below code.

Let's run app.py with the below command

 uvicorn app:app --reload 

Adding --reload to the line will enable auto-refresh to your API whenever you save new changes. You can replace the left side app with your file/module name. For example, if you create a file as main.py then your command would be uvicorn main:app --reload.

Your API is running by now, and you can access it by going to http://localhost:8000/ from your browser. To see the documentation page of your API go to Swagger - http://localhost:8000/docs or Redoc - http://localhost:8000/redoc.

Understanding the above Code Example

After creating an instance you have defined data which is a list of dictionaries (i.e. fruits) to perform CRUD (Create Read Update and Delete) operations on it (Note: you can define your own data model or even use the database directly).

You have created an API that:

  • Receives HTTP GET request in path  and  /fruits , returns welcome note and list of fruits respectively.
  • Receives HTTP GET request in path  /find/fruits/{fruit_id}  and finds fruit with given fruit ID in URL. path parameter  fruit_id  should be an integer as you have defined in the function argument.

Why end here let's add more methods to the API

The above code has a body (BaseModel class) with Pydantic for the PUT and POST method. Now save this code and your API should auto-refresh, you can perform all the CRUD operations.

You can now try integrating the Postgres (or any other) database using SQAlchemy and make it a production-ready REST API but that would be a topic for the next blog.

Thank you for visiting my blog๐Ÿ˜Š! If you enjoyed this article, you can subscribe to my blog for the latest updates. Let me know your comments about this article.

Comments

  1. Simple and easy to understand ...keep it up..

    ReplyDelete
  2. Your blog is awesome , You have explained it clearly and its a best method to create the API's using FastAPI framework , we must incorporate this method to build the API which has high performance and its easy to code! Keep up your work Sarvesh :)

    ReplyDelete

Post a Comment

Popular posts from this blog

What is Cryptography and the Process of Encryption/Decryption with Python (AES - CBC Mode)

In the IT industry, Cryptography is one of the most important techniques to secure sensitive data. According to Wikipedia Cryptography is about constructing and analyzing protocols that prevent third parties or the public from reading private messages. What this exactly means let's understand, now assume that you have a secret message that you do not want to share with any other except the receiver. Of course, you are sending the message to the receiver so he only will receive that message but what if someone manages to hack your message. In this case, if your message will be in a normal text he can easily read it, so to avoid this type of risk we encrypt our message before sending it. So that even if someone manages to hack our message he can not read the message. As per my understanding, the Encryption/Decryption or Encoding/Decoding of the message is called Cryptography. There are multiple ways to Encrypt and Decrypt the message, I will be covering here AES (Advanced Encryption...

What is Lambda (Anonymous Function) in Python and How to use it with Filter, Map & Reduce

Anonymous function means that function which does not have a name, so now we can simply say function without having a name is lambda function. To create a normal function in python we need to use the def keyword and while creating the lambda function we need to use the lambda keyword. Hope you have got a brief idea of what is lambda in Python. Normal Function: Lambda Function: Output:  Output from normal function:  25   Output from lambda function:  25  Here above-defined both function is returning the same thing but using lambda function we will be removing the uses of keywords like def, return and also we are reducing the number of lines, You can use any number of argument as you want but the expression should be only one.  Lambda function does not require a return statement because it returns the expression itself directly. Where ever you need one expression with any number of arguments you can use the lambda function without even assigning the vari...