I have read the swagger definitions and the format and understood that swagger definition is used to describe the APIs.
Would it be better to write the swagger definition and then the API? or to write the API first and then the swagger? I have no experience with this and I would like to write a REST API and a swagger file for an application.
I don't think the order really matters. Both methods are given legitimacy in the Swagger Getting Started Guide. The key thing is that one should be generated from the other, so you don't have to manually maintain both.
In the comments, cricket_007 has already mentioned that tools exist to generate the web service skeleton from the swagger definition. Using these tools, it would make sense to write the swagger definition first. This is the Top Down approach from the getting started guide.
From the Swagger getting started guide linked above, you can see that there are also tools available to generate Swagger docs from java code, provided you are using a particular framework like JAX-RS. This is the Bottom Up approach.
It comes down to personal preference. If you are the kind of person that would rather not "couple" your code base to Swagger and make sure that your application does not depend on Swagger to work, then the bottom up approach is best. However, if you want to fully embrace the Swagger tool chain and really "buy in" to it, then the top down approach is probably the best.
Also, if this is for educational purposes, then think about what you want to learn about. If you want to learn about writing JSON REST APIs from scratch (or using something like JAX-RS), then the bottom up approach will teach you more. However, if your goal is to learn as much as possible about Swagger, then the top down approach will be better.