FastAPI Fundamentals — Getting Faster with FastAPI

FastAPI Fundamentals — Getting Faster with FastAPIhttps://fastapi.tiangolo.com/FastAPI is a modern, fast (high-performance), web framework for building APIs with Python 3.7+ based on standard Python-type hints.What is an API?https://medium.com/media/d2…


This content originally appeared on Level Up Coding - Medium and was authored by Afaque Umer

FastAPI Fundamentals — Getting Faster with FastAPI

https://fastapi.tiangolo.com/

FastAPI is a modern, fast (high-performance), web framework for building APIs with Python 3.7+ based on standard Python-type hints.

What is an API?

API is the acronym for Application Programming Interface, which is a software intermediary that allows two applications to talk to each other.

In the context of APIs, Interface can be thought of as a contract of service between two applications. This contract defines how the two communicate with each other using requests and responses, these response messages could be of any supported format like XML, JSON, CSV, etc.

Imagine you went to a restaurant with your partner for a dinner date, and you want to place an order. How would you do it? Call the waiter and place an order. Now, what happens at the backend? The waiter goes to the chef and gives the order details. When the dishes are ready, he brings them to you. This is how APIs typically work. An API lets the clients access particular resources of the backend or server.

credit : https://www.analyticsvidhya.com/

Why FastAPI ?

I won’t tell you the reason why we adore FastAPI is because it is 👇

  • Fast
  • Fast to code
  • Fewer bugs
  • Intuitive
  • Easy
  • Short
  • Robust
  • Standards-based

You already know that, that’s why you are reading this 📜 right ??

How to install it?

Installation via pip

Uvicorn is an ASGI(Asynchronous Server Gateway Interface) web server implementation for Python. ASGI is a spiritual successor to WSGI, intended to provide a standard interface between async-capable Python web servers, frameworks, and applications.

Let’s create a Basic fastAPI 🚀

Create a basic python script, let’s name it main.py. Inside this, we’ll import fastAPI and create a function that will return “Hello World” when invoked through endpoints. This will ensure that we have successfully installed fastAPI and it’s up & running — The Universal goal of “Hello World” 😁

Now for running the server we need to run uvicorn in the terminal in the following syntax.

uvicorn main:app — reload

main” → is the module/script name i.e main.py ( we don’t have to write .py extension here ) & “app” → is the instance variable of the class FastAPI that we created in the above snippet.

http://127.0.0.1:8000/ 👈running this in a browser( local machine ) will fetch the response of the above API.

FastAPI provides an interactive API documentation known as Swagger UI. For running Swagger UI run → http://127.0.0.1:8000/docs in the browser. You will see the automatic interactive API documentation.

Swagger UI

So our API is returning the correct message ✅, but wait a sec what just happened here ⁉️⁉️

Understanding the Path Operation

What is a Path?

The last part of this url👉 http://127.0.0.1:8000/ which starts after 8000. So here “/” is also a path. It is also known as endpoint/route/api.

What is an Operation?

Operation refers to the HTTP Methods. There are a bunch of them but most-commonly-used HTTP methods are as follows:

POST : Create data.
GET : Retrieve/Read data.
PUT : Update the data.
DELETE : Delete data.

These operations combined together are called CRUD operations.

Coming back to our app. The “@app.get(‘/’)” decorator gives FastAPI two pieces of information. 1. It’s a GET operation. 2. The path parameter is “/”. A decorator is always defined on top of a function, which takes the function and does something with it. Here, the function base will be called by FastAPI whenever it receives a request to the URL “/” using a GET operation.

Now we know how we can create our endpoints/path and how to decorate it over any function, let’s explore some examples using GET & POST methods.

Path Parameters

A path parameter is a parameter/variable/value that we pass through our path/endpoint. We need to declare the parameter inside {} and the same variable needs to be declared in the function as a parameter. So the variable at the endpoint/path will be passed as an argument to the function.

FastAPI integrates Pydantic so we can get all the benefits of type validation using Python type annotations. We need to only define the type and need not worry about data validation behind the scenes.

Let’s create some endpoints/apis and see the response to prove the above statements.

Example 1:

API documentation — Swagger UI
Request URL & Response Body

Noticed something 👆 Even though we passed 1234 as the path parameter it was parsed as a string, what happens when we take input in a python script? Yes, the same problem we are facing here. But here, they are part of the URL, they are “naturally” strings. What happens if we pass a float or date object? Curious?? Test it out by yourself — The only way to learn !!!

Now let’s see the 2nd example where we have taken care of the type 👇.

Example 2:

API documentation — Swagger UI
Request URL & Response Body

The result is as expected 🌟. It’s because when we declare the type of data, first they are converted to that type and then validated against it. But what happens if we pass anything but int. Let’s check it out.

When passed a float
When passed a string

Query Parameters

Have you ever typed an address on the search engine only for it to return something long and sophisticated, with equals signs and question marks?

A query parameter can be defined as the optional key-value pair/pairs that appear after the “?” in the URL separated by “&” characters.

The question mark sign is used to separate path and query parameters.

Difference between Path & Query Parameters ?

  1. Path parameters appear before the “?” in the URL while the Query parameter comes after it.
  2. Path parameters identify a specific resource/resources while query parameters are used to sort/filter resources.
  3. You can’t omit values in path parameters while in the query you can.
Query parameters example

We have defined two endpoints an “/add” that requires two query parameters x & y, and we have taken care of the type using type annotation, the other one is is “/multiply” which is also the same except it has a default value,we can also define some optional parameters using None, but we’ll cover that in POST method.

When we declare parameters with Python types they are converted to that type and validated against it.

Let’s test it out in Thunder Client.

Query with type validation

the URL for “/add” is : http://127.0.0.1:8000/add?x=4&y=6

Query with default values

& the URL for “/multiply” is : http://127.0.0.1:8000/multiply, Here the URL is different and there are no “?” or “&” symbols, thanks to default values which is utilised when don’t pass any query and if we provide one it overrides the default ones. See the query below

Overriding default values

Request Body

Antipodal of Response is a request where a client needs to send data to the server side via API. To send data we usually use the POST method. Again for data validation, we use pydantic’s BaseModel. Using BaseModel we define a class/model and declare all the required data/fields and their types. If some values are initialized then it is not required otherwise required & we can make a value optional by using None. Read more about Pydantic here.

Model Class using BaseModel

Here 👆:

  1. user_id is required & needs to be an integer data type.
  2. user_age is an optional value, if passed needs to be an integer.
  3. user_name is required and needs to be a string data type.
  4. user_nick_name is required & needs to be a string when passed, if nothing is passed it has a default value as ‘Oreo’.

The type of default value sets automatically the type of field.

JSON Schema

First, we will pass all the fields.

In the above example only user_age is optional, so let’s send a request discarding the optional value.

So, this was pretty much all the basics the you need to know to get going with FastAPI. I hope you enjoyed the article. See you on another topic 👋

Thanks for reading 🙏Keep learning 🧠 Stay Awesome 🤘


FastAPI Fundamentals — Getting Faster with FastAPI was originally published in Level Up Coding on Medium, where people are continuing the conversation by highlighting and responding to this story.


This content originally appeared on Level Up Coding - Medium and was authored by Afaque Umer


Print Share Comment Cite Upload Translate Updates
APA

Afaque Umer | Sciencx (2022-10-06T14:52:11+00:00) FastAPI Fundamentals — Getting Faster with FastAPI. Retrieved from https://www.scien.cx/2022/10/06/fastapi-fundamentals-getting-faster-with-fastapi/

MLA
" » FastAPI Fundamentals — Getting Faster with FastAPI." Afaque Umer | Sciencx - Thursday October 6, 2022, https://www.scien.cx/2022/10/06/fastapi-fundamentals-getting-faster-with-fastapi/
HARVARD
Afaque Umer | Sciencx Thursday October 6, 2022 » FastAPI Fundamentals — Getting Faster with FastAPI., viewed ,<https://www.scien.cx/2022/10/06/fastapi-fundamentals-getting-faster-with-fastapi/>
VANCOUVER
Afaque Umer | Sciencx - » FastAPI Fundamentals — Getting Faster with FastAPI. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2022/10/06/fastapi-fundamentals-getting-faster-with-fastapi/
CHICAGO
" » FastAPI Fundamentals — Getting Faster with FastAPI." Afaque Umer | Sciencx - Accessed . https://www.scien.cx/2022/10/06/fastapi-fundamentals-getting-faster-with-fastapi/
IEEE
" » FastAPI Fundamentals — Getting Faster with FastAPI." Afaque Umer | Sciencx [Online]. Available: https://www.scien.cx/2022/10/06/fastapi-fundamentals-getting-faster-with-fastapi/. [Accessed: ]
rf:citation
» FastAPI Fundamentals — Getting Faster with FastAPI | Afaque Umer | Sciencx | https://www.scien.cx/2022/10/06/fastapi-fundamentals-getting-faster-with-fastapi/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.